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 }
原文地址:https://www.cnblogs.com/strengthen/p/9748036.html
时间: 2024-10-07 15:50:01