LeetCode 100. Same Tree 相同的树

题目:

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true

示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

示例 3:

输入:       1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出: false

解题思路:

对两棵树同时进行前序遍历,判断对应的每个节点是否相等,注意判断null值。

代码实现:

递归版本:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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 == null && q != null) return false;
        if (p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

非递归版本:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Stack<TreeNode> pStack = new Stack<TreeNode>();
        Stack<TreeNode> qStack = new Stack<TreeNode>();
        if (!isEqual(p, q)) return false;
        else {
            while (p != null && q != null) {
                if (isEqual(p, q)) {
                    if (p.right != null) {
                        pStack.push(p.right);
                        qStack.push(q.right);
                    }
                    p = p.left;
                    q = q.left;
                    if (p == null && q ==null && !pStack.isEmpty() && !qStack.isEmpty()) {
                        p = pStack.pop();
                        q = qStack.pop();
                    }
                } else {
                    return false;
                }
            }
            return isEqual(p, q);
        }
    }

    private boolean isEqual(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        else if (p == null && q != null) return false;
        else if (p != null && q == null) return false;
        else {
            if (p.val != q.val) return false;
            if (p.left == null && q.left != null) return false;
            else if (p.left != null && q.left == null) return false;
            if (p.right == null && q.right != null) return false;
            else if (p.right != null && q.right == null) return false;
        }
        return true;
    }
}

你可能感兴趣的:(Leetcode,(1~100))