[LeetCode By Go 83]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.

解題思路

如果樹不是空樹,則問題變為判斷根樹的兩個子樹t1,t2是否是鏡像
將t2左右翻轉后和t1比較,如果t1,t2相等,則原數是鏡像樹

代碼

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func ReverseTree(t *TreeNode) {
    if nil == t {
        return
    }
    t.Left, t.Right = t.Right, t.Left
    ReverseTree(t.Left)
    ReverseTree(t.Right)
}

func EqualTree(t1, t2 *TreeNode) bool  {
    if nil == t1 && nil == t2 {
        return true
    } else if nil != t1 && nil == t2 {
        return false 
    } else if nil == t1 && nil != t2 {
        return false 
    }
    
    if t1.Val != t2.Val {
        return false 
    }
    
    ok1 := EqualTree(t1.Left, t2.Left)
    if !ok1 {
        return false 
    }
    
    ok2 := EqualTree(t1.Right, t2.Right)
    if !ok2 {
        return false 
    }
    
    return true 
}

func isSymmetric(root *TreeNode) bool {
    if nil == root {
        return true
    }

    left := root.Left
    ReverseTree(root.Right)

    equal := EqualTree(left, root.Right)

    if equal {
        return true
    } else {
        return false
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容