二叉树深度优先遍历的多种写法

  • 递归写法
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)

引入master公式

  • 非递归写法(辅助栈)
//非递归前序遍历
//思路,用栈来模拟系统栈,因为是先进后出,所以先进右节点,再进左节点
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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值