LeetCode Same Tree

/**
 * 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代码:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isSameTree(TreeNode p, TreeNode q) {
12         return dfs(p, q);
13     }
14     
15     public boolean dfs(TreeNode root, TreeNode pair) {
16         if (root == null && pair == null) {
17             return true;
18         }
19         if (root == null || pair == null) {
20             return false;
21         }
22         if (root.val != pair.val) {
23             return false;
24         }
25         return dfs(root.left, pair.left)
26                 && dfs(root.right, pair.right);
27     }
28 }

 

posted @ 2014-06-24 14:27  卖程序的小歪  阅读(174)  评论(0编辑  收藏  举报