算法的重要性,我就很少說了吧,想去大廠,就必需要通過基礎知識和業務邏輯面試+算法面試。因此,爲了提升你們的算法能力,這個公衆號後續天天帶你們作一道算法題,題目就從LeetCode上面選 !html
今天和你們聊的問題叫作 二叉樹的中序遍歷,咱們先來看題面:node
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/面試
Given the root of a binary tree, return the inorder traversal of its nodes' values.
算法
題意

解題
# 先序
def dfs(u):
visited.append(u)
dfs(u.left)
dfs(u.right)
# 中序
def dfs(u):
dfs(u.left)
visited.append(u)
dfs(u.right)
# 後序
def dfs(u):
dfs(u.left)
dfs(u.right)
visited.append(u)數組

class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
ret = []
stack = []
stack.append(root)
while len(stack) > 0:
# 獲取棧頂頂點
cur = stack[-1]
if cur is None:
stack.pop()
continue
# 若是左孩子存在,那麼優先遍歷左孩子
if cur.left is not None:
stack.append(cur.left)
# 把左指針置爲空,防止死循環
# 這裏也能夠用set來維護
cur.left = None
continue
# 左邊遍歷結束以後加入序列
ret.append(cur.val)
stack.pop()
if cur.right is not None:
stack.append(cur.right)
return ret微信
上期推文:數據結構
本文分享自微信公衆號 - 程序IT圈(DeveloperIT)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。app