非递归实现中、后序遍历
来源:1-11 二分搜索树前序遍历的非递归实现
慕UI4021841
2020-09-18 16:48:05
根据bobo老师上一节课的分析,通过栈完全可以实现非递归的中、后序遍历
// 二叉树的中序遍历 通过栈的非递归实现 public void inOrder() { Stack<Node> stack = new Stack<>(); stack.push(root); Node left = root.left; while (left!= null){ stack.push(left); left = left.left; } // 先把左边全部节点压入栈 while (!stack.isEmpty()){ Node inCul = stack.pop(); System.out.print(inCul.e+"\t"); if (inCul.right!=null){ stack.push(inCul.right); Node temp = inCul.right.left; while (temp!= null){ stack.push(temp); temp = temp.left; } } } } // 二叉树的后序遍历 通过栈的非递归实现 public void postOrder() { Stack<Node> stack = new Stack<>(); stack.push(root); Node left = root.left; // 先把左边全部节点压入栈 while (left!= null){ stack.push(left); left = left.left; } while (!stack.isEmpty()){ Node inCul = stack.pop(); if (inCul.right!=null){ stack.push(new Node(inCul.e));//和中序遍历不同的是,这里再把当前incul压入栈 stack.push(inCul.right); Node temp = inCul.right.left; while (temp!= null){ stack.push(temp); temp = temp.left; } }else { System.out.print(inCul.e+"\t"); } } }
1回答
慕UI4021841
提问者
2020-09-18
结合bobo老师的分析,感觉算法真的好简单,感谢!@bobo老师
相似问题