?歡迎訂閱《leetcode》專欄,每日一題,每天進步?
記憶:中序遍歷不忘“左鏈入堆疊”
——leetcode此題熱評
前言
哈嘍,大家好,我是一條,
糊涂演算法,難得糊涂
今天作業中剛好遇到部門下拉樹,那就做一道中序遍歷吧!
Question
94. 二叉樹的中序遍歷
難度:簡單
給定一個二叉樹的根節點 root ,回傳它的 中序 遍歷,
示例 1:
輸入:root = [1,null,2,3] 輸出:[1,3,2]示例 2:
輸入:root = [] 輸出:[]示例 3:
輸入:root = [1] 輸出:[1]示例 4:
輸入:root = [1,2] 輸出:[2,1]示例 5:
輸入:root = [1,null,2] 輸出:[1,2]提示:
樹中節點數目在范圍 [0, 100] 內
-100 <= Node.val <= 100進階: 遞回演算法很簡單,你可以通過迭代演算法完成嗎?
Solution
二叉樹的遍歷應該算是比較基本的內容,
首先分清什么是前序、中序、后序:
- 前序遍歷:列印 - 左 - 右
- 中序遍歷:左 - 列印 - 右
- 后序遍歷:左 - 右 - 列印
實作思路也很簡單,非常典型的遞回
- 終止條件:當前節點為空時
- 函式內:遞回的呼叫左節點,列印當前節點,再遞回呼叫右節點
Code
所有
leetcode代碼已同步至github歡迎
star
/**
* @author yitiaoIT
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
Result
復雜度分析
- 時間復雜度:O(N)

🌈尋寶
?今天是堅持刷題更文的第22/100天
?各位的點贊、關注、收藏、評論、訂閱就是一條創作的最大動力
?更多演算法題歡迎關注專欄《leetcode》
為了回饋各位粉絲,禮尚往來,給大家準備了一條多年積累下來的優質資源,包括 學習視頻、面試資料、珍藏電子書等
怎么領取請大家自己找,尋寶游戲現在開始,
找不到可以評論留言,一條就會注意到你,
如果還不行,請私信我,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/292442.html
標籤:其他
