- 递归写法
public class Test {
//递归前序
public void preOrder(Node root) {
if (root == null) {
return;
}
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
//递归中序
public void InOrder(Node root) {
if (root == null) {
return;
}
preOrder(root.left);
System.out.println(root.val);
preOrder(root.right);
}
//递归后序
public void PostOrder(Node root) {
if (root == null) {
return;
}
preOrder(root.left);
preOrder(root.right);
System.out.println(root.val);
}
}
class Node {
int val;
Node left;
Node right;
}
时间复杂度:O(N)
空间复杂度:递归N层,每次的复杂度为1,所以总的空间复杂度为O(N)
- 非递归写法(辅助栈)
//非递归前序遍历
//思路,用栈来模拟系统栈,因为是先进后出,所以先进右节点,再进左节点
public static void preOrderIteration(TreeNode head) {
if (head == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.print(node.value + " ");
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}
//非递归的中序遍历
public void inOrderIteration(Node root){
Stack<Node> stack=new Stack<>();
Node cur =root;
while (!stack.isEmpty()||cur!=null){
//尽可能的放入左结点
while (cur!=null){
stack.push(cur);
cur=cur.left;
}
//此时弹出的是当前最左边的结点
Node node = stack.pop();
System.out.println(node);
//如果有右子树,则要处理右子树的遍历
if (node.right!=null){
cur=cur.right;
}
}
}
//非递归后序遍历
//利用两个栈,把后序又弄成了先序的感觉
public void postOrderIteration(Node root){
Stack<Node> stack1=new Stack<>();
Stack<Node> stack2=new Stack<>();
stack1.push(root);
while (!stack1.isEmpty()){
Node node = stack1.pop();
stack2.push(node);
if (node.left!=null){
stack1.push(node.left);
}
if (node.right!=null){
stack1.push(node.right);
}
}
while (!stack2.isEmpty()){
System.out.println(stack2.pop());
}
}
时间复杂度:由于每个节点都要进栈和出栈,所以时间复杂度为O(N)
空间复杂度:创建了辅助栈,所以空间复杂度为O(N)