leetcode:101. Symmetric Tree

2018-08-19  本文已影响0人  唐僧取经

101. Symmetric Tree

Description

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1

/
2 2
/ \ /
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/
2 2
\
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.

Answer


func validate(left *TreeNode, right *TreeNode) bool {

    //从根往下的第一步
    if left == nil && right == nil {
        return true
    }

    //判断下一层是否左右节点存在
    if left == nil || right == nil {
        return false
    }

    //判断值是否相同
    if left.Val != right.Val {
        return false
    }

    if validate(left.Left, right.Right) == false {
        return false
    }

    return validate(left.Right, right.Left)

}

func isSymmetric(root *TreeNode) bool {

    if root == nil {
        return true
    }

    return validate(root.Left, root.Right)

}



上一篇下一篇

猜你喜欢

热点阅读