題目
給定一個二叉樹,返回它的 中序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,3,2]
進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?
遞歸
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> ans;
public List<Integer> inorderTraversal(TreeNode root) {
ans = new ArrayList<>();
dfs(root);
return ans;
}
public void dfs(TreeNode root) {
if (root == null) return ;
dfs(root.left);
ans.add(root.val);
dfs(root.right);
}
}
迭代1
自己寫的迭代,就是仿造遞歸的順序寫的:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
if (root == null) return ans;
// 把最左邊的節點入棧,但並不訪問
TreeNode p = root;
while (p != null) {
stack.add(p);
p = p.left;
}
// 訪問並出棧,若有右孩子,將右孩子最左邊節點入棧
while (!stack.isEmpty()) {
p = stack.pollLast();
ans.add(p.val);
p = p.right;
while (p != null) {
stack.add(p);
p = p.left;
}
}
return ans;
}
}
迭代2
官方題解的迭代,缺點是用了Stack
,這個類是不推薦使用的,優點是比我寫的優雅T^T
public class Solution {
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList<>();
Stack < TreeNode > stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}