美文网首页
leetcode:101. Symmetric Tree

leetcode:101. Symmetric Tree

作者: 唐僧取经 | 来源:发表于2018-08-19 14:51 被阅读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)
    
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:leetcode:101. Symmetric Tree

          本文链接:https://www.haomeiwen.com/subject/lwuciftx.html