LeetCode 226 翻轉二叉樹

2022-03-26 04:45:50 字數 1367 閱讀 9441

difficulty:簡單

翻轉一棵二叉樹。

示例:

輸入:

4

/ \

2 7

/ \ / \

1 3 6 9

輸出:

4

/ \

7 2

/ \ / \

9 6 3 1

備註:

這個問題是受到 的 啟發的 :

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

solution

language:全部題目

最近這幾道題都是bfs+佇列解決的,有點感覺了。

# definition for a binary tree node.

# class treenode:

#     def __init__(self, x):

#         self.val = x

#         self.left = none

#         self.right = none

​class solution:

def inverttree(self, root: treenode) -> treenode:

if not root: return none

queue = [root]

while queue:

size = len(queue)

for i in range(size):

node = queue.pop()

if node:

node.left, node.right = node.right, node.left

return root

解法二:基於dfs+stack的解法。

class solution:

def inverttree(self, root: treenode) -> treenode:

if not root: return none

stack = [root]

while stack:

node = stack.pop()

if node:

node.left, node.right = node.right, node.left

return root

leetcode 226 翻轉二叉樹

翻轉一棵二叉樹。示例 輸入 4 2 7 1 3 6 9輸出 4 7 2 9 6 3 1備註 這個問題是受到 max howell 的 原問題 啟發的 谷歌 我們90 的工程師使用您編寫的軟體 homebrew 但是您卻無法在面試時在白板上寫出翻轉二叉樹這道題,這太糟糕了。definition for...

LeetCode 226 翻轉二叉樹

這道題目是一道很經典的關於二叉樹的演算法題,題目如下 題目的描述非常簡單,就是翻轉一棵給定的二叉樹,然而有趣的是這個備註,這個故事是 mac 系統的包管理工具 homebrew 的開發者 max howell 去谷歌面試的時候沒有做出這道面試題而遭淘汰了,所以這道題目也是引發血案的一道二叉樹題目。其...

leetcode226 翻轉二叉樹

翻轉一棵二叉樹。示例 輸入 4 2 7 1 3 6 9 輸出 4 7 2 9 6 3 1 思路 有關樹的問題要想到遞迴,遞迴的想法很簡單,將根的左右子樹互換之後,再已左右子樹為根繼續互換。遞迴最重要的就是終止條件,如果傳入的是空指標,或者葉節點,那麼不需要再遞迴了,直接返回根節點。需要注意的是,在子...