码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 对称二叉树

时间:2020-11-07 16:16:53      阅读:21      评论:0      收藏:0      [点我收藏+]

标签:ini   ref   ==   def   队列   写法   boolean   ||   for   

Leetcode 101

数据结构定义:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

递归写法:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root ==null){
            return  true;
        }
        return checkSymmetric(root.left,root.right);
    }
    
    public boolean checkSymmetric(TreeNode left,TreeNode right){
        if(left == null && right == null){
            return true;
        }
        if(left ==null || right == null){
            return false;
        }
        return left.val == right.val &&
            checkSymmetric(left.left,right.right) &&
            checkSymmetric(left.right,right.left);
    }
}

队列:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        queue.offer(root);
        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;
    }
}

Leetcode 对称二叉树

标签:ini   ref   ==   def   队列   写法   boolean   ||   for   

原文地址:https://www.cnblogs.com/CodingXu-jie/p/13936493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!