Alan Zhan 部落格

Live for nothing, or die for something

226. Invert Binary Tree

https://leetcode.com/problems/invert-binary-tree/

Easy


Given the root of a binary tree, invert the tree, and return its root.

 

Example 1:

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

題意

將整棵樹的所有左右節點互相對調。

解題思路

我們可以把每個節點都視為是一個 root 節後,然後遍例所有的 root 節點,並且將每個 root 節點的左右節點互換即可。

  1. 判斷 root 是不是為 nil ,如果是結束該 root 節點的遍例。
  2. 將該 root 的左右節點對調。
  3. 將左節點和右節點當作 root,繼續遞歸調用 invertTree 方法,直到第一步被觸發結束遍例。

原始碼

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

結尾

你有更好或更簡單的解決方案嗎?

歡迎到我的 Facebook Alan 的筆記本 留言,順手給我個讚吧!你的讚將成為我持續更新的動力,感謝你的閱讀,讓我們一起學習成為更好的自己。