100. Same Tree
- Total Accepted: 147130
- Total Submissions: 333400
- Difficulty: Easy
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.
Subscribe to see which companies asked this question
1、递归 DFS
2、不能遍历输出再比较,
10 10
/ / \
5 5 15
\
15
是不一样的。
代码:
public class Solution {
public boolean isSameTree(TreeNode p ,TreeNode q ){
if(p == null && q == null)return true;
if(p == null || q == null ||p.val != q.val) return false;
else
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
}
非递归实现参考:http://www.cnblogs.com/ganganloveu/p/4136259.html
里面用的层次遍历。