★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-cwnxwrhv-mc.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Invert a binary tree.node
Example:git
Input:github
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.
翻轉一棵二叉樹。this
示例:spa
輸入:code
4 / \ 2 7 / \ / \ 1 3 6 9
輸出:htm
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 }