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.

给定两颗二叉树,判断这两颗树是否相同,它们相同的条件是结构相同,对应节点的值也必须相同。同样采用递归的方式,先比较对应点的节点是否为空,如果都为空,那么在当前状态下返回true;如果一个空,一个不为空,返回false。如果都不为空的情况下,判断对应点的值,如果值不同返回false;如果值相同,递归判断当前节点的子树。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) {
            return true;
        } else if(p != null && q != null) {
            if(p.val != q.val) return false;
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
        return false;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276006