算法:对称的二叉树(LeetCode)

题目:请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

1

/ \

2 2

/ \ / \

3 4 4 3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

1

/ \

2 2

\ \

3 3

示例 1:

输入:root = [1,2,2,3,4,4,3]

输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]

输出:false

限制:

0 <= 节点个数 <= 1000

解题思路:将二叉树每一层都放到数组中独自判断,由左向右,为空则放空指针。

<code>/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSymmetric(root *TreeNode) bool {
    if root==nil{
        return true
    }
    tmp:=make([]*TreeNode,1)
    tmp[0]=root//根结点
    for len(tmp)>0{
        l:=len(tmp)
        for i:=0;i/<code>

执行用时 :4 ms, 在所有 Go 提交中击败了74.74%的用户

内存消耗 :3 MB, 在所有 Go 提交中击败了100.00%的用户

优化:使用递归,判断左右子树是否相等。

<code>/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSymmetric(root *TreeNode) bool {
    if root==nil{
        return true
    }
    return check(root.Left,root.Right)
}
func check(left,right *TreeNode) bool{
    if left==nil && right==nil{
        return true
    }
    if left==nil || right==nil || left.Val!=right.Val{
        return false
    }
//判断左子树的右子树是否和右子树的左子树是否相等,判断左子树的左子树和右子树的右子树是否相等。达到对称。
    return check(left.Right,right.Left) && check(left.Left,right.Right)
}/<code>

执行用时 :4 ms, 在所有 Go 提交中击败了74.74%的用户

内存消耗 :2.9 MB, 在所有 Go 提交中击败了100.00%的用户


分享到:


相關文章: