Leetcode 对称二叉树

技术文章 1年前 (2020) 完美者
363 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

版权声明:完美者 发表于 2020-11-07 16:16:53。
转载请注明:Leetcode 对称二叉树 | 完美导航

暂无评论

暂无评论...