文章 224
评论 6
浏览 200764
Tree - 101. Symmetric Tree

Tree - 101. Symmetric Tree

101. Symmetric Tree

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.

思路:

题目意思是判断一棵树是不是对称的,可以用迭代或者递归来做

代码:

go:

/**

 * Definition for a binary tree node.

 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSymmetric(root *TreeNode) bool {
    return isMirror(root, root)
}

func isMirror(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    
    if p != nil && q != nil && p.Val == q.Val {
        return isMirror(p.Left, q.Right) && isMirror(p.Right, q.Left)
    } else {
        return false
    }
    
}

标题:Tree - 101. Symmetric Tree
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/18/1566129853869.html

Nothing just happens, it's all part of a plan.

取消