LeetCode 94. Binary Tree Inorder Traversal
原题链接
中等
作者:
Ccc1Z
,
2020-07-15 19:29:24
,
所有人可见
,
阅读 520
递归
/**
* 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<>();
if(root == null)
return ans;
dfs(root);
return ans;
}
private void dfs(TreeNode root){
if(root == null)
return;
dfs(root.left);
ans.add(root.val);
dfs(root.right);
}
}
迭代
- 用栈模拟递归的过程
- 先把最左子树全部放入栈中
- 同样的在第二次回到该节点时将其放入list中
/**
* 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<>();
if(root == null)
return ans;
Stack<TreeNode> stk = new Stack<>();
TreeNode cur = root;
while(cur != null || !stk.isEmpty()){
while(cur != null){
stk.push(cur);
cur = cur.left;
}
//第二次来到cur
cur = stk.pop();
ans.add(cur.val);
cur = cur.right;
}
return ans;
}
}