Same Tree problem on leetcode
2014-11-25 21:42
267 查看
Problem Description:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
Tags: Tree, Depth-first Search
Class: Easy
Source Code:
we can solve this problem using just one line code, like this:public boolean isSameTree(TreeNode p, TreeNode q) { return p == null || q == null ? p == null && q == null : p.val != q.val ? false : isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }
Although the solution is clean, However, it is difficult to read. Don't worry, we can rewrite it to a more understandable form, like this:
public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null || q == null) return p == null && q == null; else if (p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); else return false; }
cnblogs did a bad job on support for Markdown, you can find a more beautiful composing here
相关文章推荐
- leetcode 65: Same Tree
- WHU1461(A problem on tree)贪心+找规律
- LeetCode之Same Tree
- [leetcode]Same Tree @ Python
- [leetcode]_Same Tree
- LeetCode: Same Tree
- LeetCode Same Tree
- LeetCode Same Tree
- LeetCode之Same Tree
- LeetCode: Same Tree [100]
- leetcode: Same Tree
- [LeetCode]Same Tree解题报告
- [leetcode.com]算法题目 - Same Tree
- LeetCode Same Tree
- LeetCode -- Same Tree 代码分析
- leetcode 65: Same Tree
- leetcode之same tree
- Same Tree [LeetCode]
- Leetcode: Same Tree 理解分析
- LeetCode:Same Tree