1.二叉树数的前序非递归遍历
public List<Integer> preOrder(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null)
return list;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
list.add(temp.val);
stack.add(temp);
if (temp.left != null) {
stack.add(temp.left);
}
if(temp.right != null) {
stack.add(temp.right);
}
}
return list;
}
2.二叉树的中序非递归遍历
public List<Integer> InOrder(TreeNode root){
List<Integer> list = new ArrayList<>();
if(root == null)
return list;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
do {
while(cur != null) { //让左节点一直入栈,知道左子树为空
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
list.add(cur.val);
if(cur.right != null) {
cur = cur.right; //如果出现的节点有右子树,则指向右子树
}else {
cur = null; //设置为空,下次循环继续出栈
}
}while(!stack.isEmpty() || cur != null);
return list;
}
3.二叉树的后序非递归遍历
//借助两个栈实现
public List<Integer> PostOrder(TreeNode root){
List<Integer> list = new ArrayList<>();
if(root == null)
return list;
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.add(root);
while(!stack1.isEmpty()) {
TreeNode node = stack1.pop();
stack2.add(node);
if(node.left != null) {
stack1.add(node.left);
}
if(node.right != null) {
stack1.add(node.right);
}
}
while(!stack2.isEmpty()) {
TreeNode temp = stack2.pop();
list.add(temp.val);
}
return list;
}