Same Tree

100. Same Tree

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

 

沒什麼特別解法,就是用遞迴方式做 DFS 一個個 node 去做比較,都一樣就返回 true

public boolean isSameTree(TreeNode p, TreeNode q) {
    if(p == null && q==null) {
        return true;
    } else if(p == null || q == null) {
        return false;
    }

    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}