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.
Solution: Maybe this is the easiest problem in LeetCode...

Non-recursive version will be more complicated, but unnecessary. It requires any kind of tree traversal and then compare two trees.
Following code passes the LeetCode Online Large Judge.
/**
 * 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) {
        if(p == NULL || q == NULL) return !((p == NULL)^(q == NULL));
        if(p->val != q->val) return false;
        else return isSameTree(p->left, q->left) && 
                isSameTree(p->right, q->right);
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 4 Trees and Graphs