100. 相同的树

深度优先搜索

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {

        /**
         * 除非p和q共同为null或者都不为null,否则返回false
         */
        if (p == null || q == null){
            return p == q;
        }

        /**
         * 后序遍历
         * 如果根节点的子树满足条件,最后判断根节点是否满足条件
         */
        if (isSameTree(p.left, q.left) && isSameTree(p.right, q.right)){
            return p.val == q.val;
        }
        else {
            return false;
        }
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

迭代(栈)

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {

        /**
         * 和《101. 对称二叉树》几乎一样
         * 使用队列也行
         */
        Stack<TreeNode> stack = new Stack<>();

        stack.push(p);
        stack.push(q);

        while (!stack.isEmpty()){

            TreeNode left = stack.pop();
            TreeNode right = stack.pop();

            if (left != null && right != null){

                if (left.val == right.val){
                    
                    stack.push(left.left);
                    stack.push(right.left);
                    stack.push(left.right);
                    stack.push(right.right);
                }
                else {
                    return false;
                }
            }
            else if (left == null && right == null){
                continue;
            }
            else {
                return false;
            }
        }
        
        return true;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/same-tree/

posted @ 2021-10-27 17:03  振袖秋枫问红叶  阅读(38)  评论(0)    收藏  举报