LeetCode 100. Same Tree(相同的树)

原题网址:https://leetcode.com/problems/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.

方法:自顶向下,递归。

/**
 * 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;
        if (p == null || q == null) return false;
        if (p.val != q.val) return false;
        if (p.left != null || q.left != null) {
            if (p.left == null || q.left == null) return false;
            if (!isSameTree(p.left, q.left)) return false;
        }
        if (p.right != null || q.right != null) {
            if (p.right == null || q.right == null) return false;
            if (!isSameTree(p.right, q.right)) return false;
        }
        return true;
    }
}


你可能感兴趣的:(树,二叉树,递归,自顶向下,校验,比较)