二叉树中序遍历
主要思想
- 整棵树的左节点进栈,直至左节点为空
- 依次弹出节点。打印。
- 对弹出节点的右树进行同样的操作
代码实现
package com.vitamin.tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MiddleOrderTree {
public List<Integer> middleOrder(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
TreeNode pop = stack.pop();
list.add(pop.val);
current = pop.right;
}
}
return list;
}
}