[leetcode]_Symmetric Tree

第二道树的题目,依旧不会做,谷歌经验。

题目解释: give you a tree , judge if it is a symmetric tree.

思路:我以为要写个中序遍历(进阶学习非递归算法)什么的,Wrong Answer。

解题思路:如果 左子树的值 等于 右子树的值,并且该左子树的左子树 等于 该右子树的右子树,并且该左子树的右子树 等于 该右子树的左子树 时,该树为symmetric。(如果tree == null || tree中只有一个节点,return true)

代码:

public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        
        return isSymmetricRecursive(root.left , root.right);
    }
    
    public boolean isSymmetricRecursive(TreeNode left , TreeNode right){
        if(left != null && right != null){
           return left.val == right.val && isSymmetricRecursive(left.left , right.right) 
                                        && isSymmetricRecursive(left.right , right.left);
        }else if(left != null || right != null) return false;
         else return true;
    }

收获:关于树的求解,多考虑 递归 方法,递归 代码简单,思路直接。进阶需要学习树的非递归方法。

原文地址:https://www.cnblogs.com/glamourousGirl/p/3728555.html