100. 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.

链接: http://leetcode.com/problems/same-tree/

题解:判断二叉树是否相同。 假如根节点都为空,则返回true; 根节点仅有一个为空,返回false; 根节点值相同,recursively比较两个子节点; 根节点值不同返回false。

Time Complexity - O(n), Space Complexity - O(1)

public class Solution {

    public boolean isSameTree(TreeNode p, TreeNode q) {

        if(p == null && q == null)

            return true;

        if(p == null || q == null)

            return false;

        if(p.val == q.val)

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

        else

            return false;

    }

}

 

测试:

你可能感兴趣的:(tree)