[leetcode] 101. 对称二叉树

101. 对称二叉树

一开始想复杂了呀,没有做出来

直观的思路就是反转这颗树,然后判断两颗树是不是相同的

class Solution {

    // 反转并创建一颗树
    public TreeNode reverseTreeNode(TreeNode root) {
        if (null == root) return null;
        TreeNode tmp = new TreeNode(root.val);
        tmp.left = reverseTreeNode(root.right);
        tmp.right = reverseTreeNode(root.left);

        return tmp;
    }

    public boolean isSame(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 == null) return true;
        if (t1 == null || t2 == null) return false;
        if (t1.val != t2.val) return false;
        else return isSame(t1.left,t2.left) && isSame(t1.right,t2.right);
    }


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

        TreeNode newTree = reverseTreeNode(root);

        return isSame(newTree,root);
    }
}

网上大部分人的思路更为简洁,一开始没有想到。
即,判断左子树和右子树是否对称:

  1. 当前左右值是否相同
  2. 当前左子树的左子树和右子树的右子树是否相同
  3. 当前左子树的右子树和右子树的左子树是否相同
    (画画图就看出来了)
    利用了二叉树的特性把
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isSymmetric(root.left, root.right);
    }
    public static boolean isSymmetric(TreeNode left, TreeNode right) {
        if(left == null && right == null) return true;
        if(left == null || right == null) return false;
        if(left.val == right.val) return isSymmetric(left.left, right.right)
                && isSymmetric(left.right, right.left);
        return false;
    }
}
posted @ 2018-11-06 17:06 ACBingo 阅读(...) 评论(...) 编辑 收藏