其他分享
首页 > 其他分享> > 力扣101题(对称二叉树)

力扣101题(对称二叉树)

作者:互联网

101、对称二叉树

基本思想:

比较的是两个子树的里侧和外侧

 

遍历顺序为后序遍历,

因为要通过递归函数的返回值来判断两个子树的内侧节点和外侧节点是否相等

一个树的遍历顺序是左右中,一个树的遍历顺序是右左中

具体实现:

1.确定递归函数的参数和返回值

参数:左子树节点和右子树节点

返回值:布尔类型

2.确定终止条件

3.确定单层递归逻辑

单层递归的逻辑就是处理左右节点都不为空,且数值相等的情况

代码:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left,root.right);
    }
    private boolean compare(TreeNode left, TreeNode right){
        if (left == null && right != null) return false;
        if (left != null && right == null) return false;
        if (left == null && right == null) return true;
        if (left.val != right.val) return false;
        boolean compareOutsize = compare(left.left, right.right);
        boolean compareInside = compare(left.right, right.left);
        return compareInside && compareOutsize;
    }
}

 

 

双端队列

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offerFirst(root.left);
        deque.offerLast(root.right);
        while (!deque.isEmpty()){
            TreeNode leftNode = deque.pollFirst();
            TreeNode rightNode = deque.pollLast();
            if (leftNode == null && rightNode == null) continue;
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) return false;
            deque.offerFirst(leftNode.left);
            deque.offerFirst(leftNode.right);
            deque.offerLast(rightNode.right);
            deque.offerLast(rightNode.left);
        }
        return true;
    }
}

 

普通队列(迭代法)

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> deque = new LinkedList<>();
        deque.offer(root.left);
        deque.offer(root.right);
        while (!deque.isEmpty()){
            TreeNode leftNode = deque.poll();
            TreeNode rightNode = deque.poll();
            if (leftNode == null && rightNode == null) continue;
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val)  return false;
            // 这里顺序与使用Deque不同
            deque.offer(leftNode.left);
            deque.offer(rightNode.right);
            deque.offer(leftNode.right);
            deque.offer(rightNode.left);
        }
        return true;
    }
}

 

标签:deque,leftNode,right,return,null,力扣,二叉树,101,left
来源: https://www.cnblogs.com/zhaojiayu/p/15521053.html