您的位置:首页 > 其它

LeetCode Same Tree

2014-06-24 14:27 232 查看
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
int v = ((p == NULL) << 1) + (q == NULL);
if (v == 0x2 || v == 0x1) return false; // one NULL the other not NULL
if (v == 0x3) return true;              // both NULL
if (p->val != q->val) return false;     // value not match
return isSameTree(p->left, q->left)     // check subtree
&& isSameTree(p->right, q->right);
}
};


继续水

第二轮:

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.

来一发Java代码:

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return dfs(p, q);
}

public boolean dfs(TreeNode root, TreeNode pair) {
if (root == null && pair == null) {
return true;
}
if (root == null || pair == null) {
return false;
}
if (root.val != pair.val) {
return false;
}
return dfs(root.left, pair.left)
&& dfs(root.right, pair.right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: