首页 > 牛客题霸-判读二叉树是否对称-Java题解
头像
点一把🔥炬
编辑于 2020-11-27 19:52
+ 关注

牛客题霸-判读二叉树是否对称-Java题解

题目:https://www.nowcoder.com/practice/1b0b7f371eae4204bc4a7570c84c2de1

  • 题解:这道题需要注意的地方就是对称的意思的理解,当root的左右孩子left和right的数值相等,同时left.left和right.right以及left.right和right.left分别对应对称时,root是对称的。这道题可以使用递归和迭代(使用队列)来做,具体可参见代码

  • java代码实现:

    import java.util.*;
    public class Solution {
    //递归
    public boolean isSymmetric (TreeNode root) {
        if(root == null)
            return true;
        return check(root.left, root.right);
    }
    
    public boolean check(TreeNode left, TreeNode right){
        if(left == null && right == null)
            return true;
        if(left == null || right == null)
            return false;
        return left.val == right.val && check(left.left, right.right) && check(left.right, right.left);
    }
    
    //迭代
    public boolean isSymmetric (TreeNode root) {
        if(root == null)
            return true;
        Queue queue = new LinkedList();
        queue.offer(root.left);
        queue.offer(root.right);
        while(!queue.isEmpty()){
            TreeNode left = queue.poll();
            TreeNode right = queue.poll();
            if(left == null && right == null)
                continue;
            if(left == null || right == null || left.val != right.val)
                return false;
            queue.offer(left.left);
            queue.offer(right.right);
            queue.offer(left.right);
            queue.offer(right.left);
        }
        return true;
    }
    }

全部评论

(0) 回帖
加载中...
话题 回帖

相关热帖

近期热帖

近期精华帖

热门推荐