数据结构每日一练【二叉树的基础面试题】
1.二叉树的前序遍历(非递归)
public void preorderNor(TreeNode root){
if (root == null){return;}
TreeNode cur = root;
TreeNode top = null;
Stack<TreeNode> stack = new Stack<>();
while (cur != null || !stack.isEmpty()){
while (cur != null){
stack.push(cur);
System.out.print(cur.val+" ");
cur =cur.left;
}
top = stack.pop();
cur = top.right;
}
}
2.二叉树的中序遍历(非递归)
void midNor(TreeNode root){
if (root == null){
return;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode top = null;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
top = stack.pop();
System.out.print(top.val + " ");
cur = top.right;
}
}
3.二叉树的后序遍历(非递归)
void postorderNor(TreeNode root){
if (root == null){return; }
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode prev = null;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.peek();
// 当cur的左右都为空,就打印cur,或者cur的右边已经打印过了,也可以打印cur
if (cur.right == null || cur.right == prev){
System.out.print(cur.val+" ");
prev = cur;
cur = null;
}else {
cur = cur.right;
}
}
}
4.二叉树之字型打印(非递归)
-
题目链接
二叉树“之”字型打印 -
题目描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}
返回值:
[[1],[3,2],[4,5]]
说明:
如题面解释,第一层是根节点,从左到右打印结果,第二层从右到左,第三层从左到右。 -
题目分析
- 当前层左到右遍历,下一层需要右到左遍历,就将下一层left–>right入栈
- 当前层右到左遍历,下一层需要左到右遍历,就将下一层right–>left入栈
- queue作为从二叉树中取出元素,暂时存储等待入栈的元素
- flag = 1表示当前层从left—>right遍历,flag = 2,表示当前层从right—>left遍历
- 运行代码
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
if(pRoot == null){
return result;
}
Stack<TreeNode> st = new Stack<>();
Queue<TreeNode> qu = new LinkedList<>();//临时存储
st.push(pRoot);
int flag = 1;//1:代表left->right式入栈. 2: 代表right->left式入栈
ArrayList<Integer> list = new ArrayList<>();//保存一层结果的临时变量
while(!st.isEmpty()){
int size = st.size();//获取当前层的个数
for(int i=0;i<size;i++){
TreeNode cur = st.pop();
list.add(cur.val);
TreeNode first = flag==1?cur.left:cur.right;
TreeNode second = flag==1?cur.right:cur.left;
if(first!=null)qu.offer(first);
if(second!=null)qu.offer(second);
}
//走到这里,一层已经遍历结束了,值都放在list里面了
result.add(new ArrayList(list));
//把结果放进result之后,要把list清空,才能继续为下一层存储
list.clear();
//把队列中等待的值,循环放入栈中
while(!qu.isEmpty()){
st.push(qu.poll());
}
//这一层是从左到右的话,下一层要换方向
flag = (flag==1)?2:1;
}
return result;
}