轉載請注明出處:http://blog.csdn.net/crazy1235/article/details/51541570
出處:https://leetcode.com/problems/same-tree/
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.
判斷兩個2叉樹是不是1樣(結構1樣,每一個對應的結點的值也是1樣)。
遞歸遍歷
/**
* 0ms
*
* @param p
* @param q
* @return
*/
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null & q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
} else {
return false;
}
}
方法簡單死了~
https://leetcode.com/discuss/69708/one-line-java-solution
public boolean isSameTree2(TreeNode p, TreeNode q) {
return (p != null && q != null && p.val == q.val
&& isSameTree2(p.left, q.left) && isSameTree2(p.right, q.right))
|| (p == null && q == null);
}
該方法只是方法1的變形。雖然只是1句話,但是沒有方法1結構清晰。
bingo~~