二叉树遍历六种方法(含递归和循环)

二叉树遍历六种方法(含递归和循环)


刷算法题必备基础知识!!!!

//前序遍历(递归)
public static void printTreeFirstRoot(BinaryTreeNode treeRoot){
        if(treeRoot == null){
            return;
        }     
        System.out.println(treeRoot.getValue());
        printTreeFirstRoot(treeRoot.leftNode);
        printTreeFirstRoot(treeRoot.rightNode);
}
//中序遍历(递归)
public static void printTreeSecoundRoot(BinaryTreeNode treeRoot){
        if(treeRoot == null){
            return;
        }
        printTreeSecoundRoot(treeRoot.leftNode);
        System.out.println(treeRoot.getValue());
        printTreeSecoundRoot(treeRoot.rightNode);
}
//后续遍历(递归)
public static void printTreeThiredRoot(BinaryTreeNode treeRoot){
        if(treeRoot == null){
            return;
        }
        printTreeThiredRoot(treeRoot.leftNode);
        printTreeThiredRoot(treeRoot.rightNode);
        System.out.println(treeRoot.getValue());
}
//先序遍历(循环)
private static void preOrderTraversal_cir(Node root) {
		if (root == null) {
			System.out.println("树为空");
			return;
		}
		Stack<Node> stack = new Stack<Node>();
		System.out.print("先序遍历:");
		while (root != null || !stack.isEmpty()) {
			if (root != null) {
				stack.push(root);
				System.out.print(root.val + " ");
				root = root.left;
			} else {
				root = stack.pop();
				root = root.right;
			}
		}
		System.out.println();
	}
//中序遍历
private static void inOrderTraversal_cir(Node root) {
		if (root == null) {
			System.out.println("树为空");
			return;
		}
 
		Stack<Node> stack = new Stack<Node>();
		System.out.print("中序遍历:");
		while (root != null || !stack.isEmpty()) {
			if (root != null) {
				stack.push(root);
				root = root.left;
			} else {
				root = stack.pop();
				System.out.print(root.val + " ");
				root = root.right;
			}
		}
		System.out.println();
	}
//后序遍历,注意比较难
private static void postOrderTraversal_cir(Node root) {
		if (root == null) {
			System.out.println("树为空");
			return;
		}
		System.out.print("后序遍历:");
		Stack<Node> stack = new Stack<Node>();
		Stack<Node> output = new Stack<Node>();
		while (root != null || !stack.isEmpty()) {
			if (root != null) {
				stack.push(root);
				output.push(root);
				root=root.right;//先让右子树压栈
			}else{
				root=stack.pop();
				root=root.left;
			}
		}
		while(!output.isEmpty()){
			System.out.print(output.pop().val+" ");
		}
		System.out.println();
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值