PS:文章最后附上完整代码
一、中序遍历
List<Integer> inOrder(BTree root) {
List<Integer> result = new ArrayList<>();
Stack<BTree> stack = new Stack<>();
BTree node;
while (null != root || !stack.empty()) {
while (null != root) {
stack.push(root);
root = root.left;
}
node = stack.pop();
result.add(node.val);
if (null != node.right) {
root = node.right;
}
}
return result;
}
二、前序遍历
List<Integer> preOrder(BTree root) {
List<Integer> result = new ArrayList<>();
Stack<BTree> stack = new Stack<>();
BTree node;