1. 程式人生 > >226. 翻轉二叉樹 | Invert Binary Tree

226. 翻轉二叉樹 | Invert Binary Tree

ble use homebrew spi brew home .com wro emp

Invert a binary tree.

Example:

Input:

     4
   /     2     7
 / \   / 1   3 6   9

Output:

     4
   /     7     2
 / \   / 9   6 3   1

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.


翻轉一棵二叉樹。

示例:

輸入:

     4
   /     2     7
 / \   / 1   3 6   9

輸出:

     4
   /     7     2
 / \   / 9   6 3   1

備註:
這個問題是受到 Max Howell 的 原問題 啟發的 :

谷歌:我們90%的工程師使用您編寫的軟件(Homebrew),但是您卻無法在面試時在白板上寫出翻轉二叉樹這道題,這太糟糕了。

12ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func invertTree(_ root: TreeNode?) -> TreeNode? {
16 guard let root = root else {return nil} 17 let left = invertTree(root.left) 18 let right = invertTree(root.right) 19 root.left = right 20 root.right = left 21 return root 22 } 23 }

8ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func invertTree(_ root: TreeNode?) -> TreeNode? {
16         if root == nil {
17             return root
18         }else{
19             let temp = root?.left
20             root?.left = invertTree(root?.right)
21             root?.right = invertTree(temp)
22             return root
23         }
24     }
25 }


12ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func invertTree(_ root: TreeNode?) -> TreeNode? {
16         if root == nil {
17         return root
18     }
19     
20     var temp: TreeNode?
21     
22     if root?.left?.left != nil || root?.left?.right != nil {
23         temp = invertTree(root?.left)
24     }else {
25         temp = root?.left
26     }
27     if (root?.right?.left != nil || root?.right?.right != nil ){
28         root?.left = invertTree(root?.right)
29     }else {
30         root?.left = root?.right
31     }
32     root?.right = temp
33     
34     return root
35         
36     }
37 }

226. 翻轉二叉樹 | Invert Binary Tree