Tree - 101. Symmetric Tree

5

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
    }
    
}