Tree - 101. Symmetric Tree

时间:2022-07-25
本文章向大家介绍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
    }
    
}