关于leetcode:对称二叉树递归和迭代

38次阅读

共计 888 个字符,预计需要花费 3 分钟才能阅读完成。

递归

/**
 * 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) {return check(root, root);
    }

    public boolean check(TreeNode a, TreeNode b) {if(a == null && b == null) {return true;}
        if(a == null || b == null) {return false;}
        return  a.val == b.val && check(a.left, b.right) && check(a.right, b.left);
    }
}

迭代

/**
 * 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) {Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        queue.offer(root);
        while(!queue.isEmpty()) {TreeNode a = queue.poll();
            TreeNode b = queue.poll();
            if(a==null && b==null){continue;}
            if(a==null || b==null){return false;}
            if(a.val != b.val) {return false;}
            queue.offer(a.left);
            queue.offer(b.right);
            queue.offer(a.right);
            queue.offer(b.left);
        }
        return true;
    }
}

正文完
 0