leetcode-101-对称二叉树

描述:

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

 

题解

/**
 * 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;
        }

        if (root.left == null && root.right == null) {
            return true;
        }

        if (root.left == null || root.right == null) {
            return false;
        }

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

        return isSymmetric(root.left) && isSymmetric(root.right);
    }
}

 

递归解该题, 时间复杂度o(N),空间复杂度o(N)-数的高度在最糟糕的情况下是N,队规调用造成的空间复杂度O(N)

 

参考: https://leetcode-cn.com/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode/

posted on 2020-03-31 19:52  wangsong412  阅读(101)  评论(0编辑  收藏  举报