【Lintcode】469. Same Tree

Title address:

https://www.lintcode.com/problem/same-tree/description

Given two binary trees, determine whether the two binary trees are the same. The same definition is that the structure of the tree and the value of each node are the same.

You can use divide and conquer. If both trees are empty, return true, otherwise if only one tree is empty, return false, then determine whether the roots are equal, and then determine whether the left and right subtrees are the same. code show as below:

public class Solution {
    /**
     * @param a: the root of binary tree a.
     * @param b: the root of binary tree b.
     * @return: true if they are identical, or false.
     */
    public boolean isIdentical(TreeNode a, TreeNode b) {
        // write your code here
        if (a == null && b == null) {
            return true;
        } else if (a == null || b == null) {
            return false;
        }
        
        return a.val == b.val && isIdentical(a.left, b.left) && isIdentical(a.right, b.right);
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

time complexity THE ( n ) O (n) , space THE ( h ) O(h)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105466671