二叉树迭代:
遍历左子树
无论左子树为空还是右子树为空:
- 出栈操作
- 访问右子树
public String preOrder(TreeNode root) {
StringBuffer sb = new StringBuffer();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
while (p != null || !stack.isEmpty()) {
while (p != null) {//访问左子树
sb.append(p.val);
stack.push(p);
p = p.left;
}
if (!stack.isEmpty()) {//出栈操作
p = stack.pop();
p = p.right;
}
}
return sb.toString();
}