LeetCode – Symmetric Tree Solution

题目:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Follow up: Solve it both recursively and iteratively.

实现:

  • 递归方式, 判断左子树的左节点和右子树右节点值是否相等, 判断左子树的右节点和右子树左节点值是否相等   空间复杂度O(N)    时间复杂度 O(N)          
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return helper(root.left, root.right);
    
        
    }
    public boolean helper(TreeNode l, TreeNode r){
        if (l == null && r == null){
            return true;
        }
        else if (l == null || r == null){
            return false;
        }
        return (l.val == r.val) && helper(l.right, r.left) && helper(l.left, r.right);
    }
}
  • 迭代方式,按照左子树右节点,左节点,右子树的左节点, 右节点,就是每层要比较的顺序, 分别放入各自队列, 再同时弹出队列, 由于不是满二叉树, 每层有空的情况, 所以如果出队列节点全为空,需要继续。    空间复杂度O(N)    时间复杂度 O(N)
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        Queue<TreeNode> ql = new LinkedList<>();
        Queue<TreeNode> qr = new LinkedList<>();
        
        ql.offer(root.left);
        qr.offer(root.right);
        
        while (!ql.isEmpty() && !qr.isEmpty()){
            TreeNode lnode = ql.poll();
            TreeNode rnode = qr.poll();
            
            if (lnode == null && rnode == null){
                continue;
            }
            else if (lnode == null || rnode == null){
                return false;
            }
            else if (lnode.val != rnode.val){
                return false;
            }
            ql.offer(lnode.left);
            ql.offer(lnode.right);
            qr.offer(rnode.right);
            qr.offer(rnode.left);
        }
        return true;
    }
}

Be First to Comment

发表回复