Symmetric Tree

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

答案

Recursive

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return recur(root.left, root.right);
    }
    
    private boolean recur(TreeNode l, TreeNode r) {
        if(l == null && r == null) return true;
        if(l == null && r != null) return false;
        if(l != null && r == null) return false;
        if(l.val != r.val) return false;
        
        return recur(l.left, r.right) && recur(l.right, r.left);
    }
    
}

Iterative

    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        Stack stk = new Stack();

        stk.push(root.left);
        stk.push(root.right);
        while(!stk.isEmpty()) {
            TreeNode r = stk.pop();
            TreeNode l = stk.pop();
            
            if(l == null && r == null) continue;
            if((l == null && r != null) || (l != null && r == null) || (l.val != r.val))
                return false;
            
            stk.push(l.left);
            stk.push(r.right);
            stk.push(l.right);
            stk.push(r.left);
            
        }
        return true;
    }

你可能感兴趣的:(Symmetric Tree)