LeetCode 94. 【Java】94. Binary Tree Inorder Traversal
原题链接
中等
作者:
tt2767
,
2020-02-03 13:48:23
,
所有人可见
,
阅读 844
/*
if (root == null) return ;
1. 看下递归的写法,每次把左子树节点压入栈中
recursive(root.left, list);
2. 左子节点全入栈后输出栈顶节点
list.add(root.val);
3. 把当前节点的右子节点压入栈中
recursive(root.right, list);
4. 当前节点弹出栈
*/
/**
* 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> list = new ArrayList<>();
iteratively(root, list);
return list;
}
public void iteratively(TreeNode root, List<Integer> list){
Stack<TreeNode> stack = new Stack<>();
var p = root;
// while(p != null && !stack.empty()){
while(p != null || !stack.empty()){
while (p != null){
stack.add(p);
p = p.left;
}
p = stack.pop();
list.add(p.val);
p = p.right;
}
return ;
}
public void iterativelyError(TreeNode root, List<Integer> list){
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
// 这样不ok,因为java只能操作指针的值,不能把对应地址置为null;
// 即使可以也破坏了原树结构
while(!stack.empty()){
var node = stack.peek();
if (node.left != null) stack.add(node.left);
else {
list.add(node.val);
stack.pop();
if (node.right != null) stack.add(node.right);
node = null;
}
}
return ;
}
public void recursive(TreeNode root, List<Integer> list){
if (root == null) return ;
recursive(root.left, list);
list.add(root.val);
recursive(root.right, list);
}
}