面试题28. 对称的二叉树

题目来源

面试题28. 对称的二叉树

题目描述

面试题28. 对称的二叉树_第1张图片

题目解析

递归

/**
 * 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 helper(root.left, root.right);
    }
    
    private boolean  helper(TreeNode left, TreeNode right){
        if (left == null && right == null){
            return true;
        }
        
        if (left == null ){
            return false; 
        }
        
        if (right == null){
            return false;
        }
        
        if (right.val != left.val){
            return false;
        }
        
        return helper(left.left, right.right) && helper(left.right, right.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) {
        if (root == null){
            return true;
        }

        
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root.right);
        stack.push(root.left);
        while (!stack.empty()){
            TreeNode left = stack.pop();
            TreeNode right = stack.pop();

            if (left == null && right == null){
                continue;
            }
            
            if (left == null){
                return false;
            }
            
            if (right == null){
                return false;
            }

            if (left.val != right.val){
                return false;
            }
            
            stack.push(left.left);
            stack.push(right.right);

            stack.push(left.right);
            stack.push(right.left);
        }

        return true;
    }
}

在这里插入图片描述

你可能感兴趣的:(算法与数据结构)