一、前中后序遍历迭代统一写法。
1.大致思路:将二叉树进行遍历,并且按前中后序的顺序压入栈中,然后按照出栈的顺序进行处理。比如将前序遍历为例,首先把第一个结点压入栈中,这时候可以知道该栈的左右结点都没有处理,所以要把该结点出栈,然后按照右孩子、左孩子、中结点的顺序压入栈中,因为出栈的时候是相反的,然后在中结点后面在压入一个空结点,这意味着该结点的左右孩子都处理完了,下次出栈遇到null说明该结点的前面的结点都已经处理完毕,那么就可以输出该结点。
2.伪代码:
stack.push(root);
while(!stack.isEmpty()){
Treenode k = stack.top();//查看是否是空指针
if( k != null ){//如果不是空指针说该结点左右孩子还没有处理,进行处理
stack.pop();
if(k.right)stack.push(k.right);
if(k.left)stack.push(k.left);
stack.push(k);stack.push(null);
}
else{//是空指针直接输出即可。
stack.pop();
sout(stack.pop());}
}
3.可运行代码
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack();
List<Integer> list = new ArrayList();
if(root == null)return list;
stack.push(root);
while(!stack.isEmpty()){
TreeNode temp = stack.peek();
if(temp != null){
stack.pop();
if(temp.right != null)stack.push(temp.right);
stack.push(temp);
if(temp.left != null)stack.push(temp.left);
}
else{
stack.pop();
list.add(stack.pop().val);
}
}
return list;
}
}
二、层序遍历
力扣102:
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
1.思路分析:通过一个队列,首先将根结点入队,然后判断队列是否为空,不为空则出队,并对该结点进行处理,首先将该结点的左右结点入队,再将该结点输出。
;2.注意:输出的要求是每一层的结点输出是一个结果,所以还要加上一个判断同一层结点的条件。所以这时候需要用队列中的个数进行判断是否为同一层。
3.伪代码
queue.push(root)
while(!queue.isEmpty()){
int k = queue.length();//k为该层的个数,用来判断是否为同一层
for(int i = 0;i < k;i++){//该k个都是同一层放在同一个list中,
Treenode temp = queue.pop();
if(temp.left)queue.push(temp.left);
if(temp.right)queue.push(temp.right);
list.add(temp.val)}
result.add(list);//同一层的数据处理完,加入到最后的result中。
}
3.代码
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> prelist = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root == null) return prelist;
queue.offer(root);
int size = 1;
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < size;i++){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null)queue.offer(node.left);
if(node.right != null)queue.offer(node.right);
}
prelist.add(list);
size = queue.size();
}
return prelist;
}
}