数据结构——前中后序遍历,迭代法java实现
迭代法实现二叉树的遍历,实际上就是在维护一个栈,利用栈“先进后出”的特点来实现遍历。
前序遍历
根->左->右
1 class Solution {
2 public List<Integer> preorderTraversal(TreeNode root) {
3 if (root == null) return Collections.emptyList();
4 List<Integer> res = new ArrayList<>(); //建一个数组,来存储要输出的结果
5 Stack<TreeNode> call = new Stack<>(); //创建维护一个栈
6 call.push(root); //先将根结点入栈
7 while (!call.isEmpty()) {
8 TreeNode t = call.pop(); //弹出结点并判断是否访问过
9 //非空说明没访问过,然后右结点入栈,左结点入栈,最后根节点入栈,并入栈一个空结点
10 //表明当前结点以访问过
11 if (t != null) {
12 if (t.right != null) call.push(t.right);
13 if (t.left != null) call.push(t.left);
14 call.push(t);
15 call.push(null);
16 } else {
17 res.add(call.pop().val); //如果弹出结点为空结点,表明当前栈顶结点已访问过
18 }
19 }
20 return res;
21 }
22 }
中序遍历
左->根->右
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return Collections.emptyList();
List<Integer> res = new ArrayList<>(); //保存结果
Stack<TreeNode> call = new Stack<>(); //调用栈
call.push(root); //先将根结点入栈
while (!call.isEmpty()) {
TreeNode t = call.pop();
if (t != null) {
if (t.right != null) call.push(t.right);
call.push(t); //在左结点之前重新插入该结点,以便在左结点之后处理(访问值)
call.push(null); //空结点随之入栈,标识已经访问过,但还没有被处理(还可以进行额外操作)
if (t.left != null) call.push(t.left);
} else {
res.add(call.pop().val);
}
}
return res;
}
}
后序遍历
左->右->根
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) return Collections.emptyList();
List<Integer> res = new ArrayList<>(); //保存结果
Stack<TreeNode> call = new Stack<>(); //调用栈
call.push(root); //先将根结点入栈
while (!call.isEmpty()) {
TreeNode t = call.pop();
if (t != null) {
call.push(t); //完全模拟递归,真的是秒杀全场
call.push(null); //!完美
if (t.right != null) call.push(t.right);
if (t.left != null) call.push(t.left);
} else {
res.add(call.pop().val);
}
}
return res;
}
}
浙公网安备 33010602011771号