二叉树的遍历

二叉树的遍历

1.递归写法

先序遍历

public void preOrder(TreeNode root) {
		if (root == null)
			return;
		System.out.print(root.val + " ");
		preOrder(root.left);
		preOrder(root.right);
	}

中序遍历

public void inOrder(TreeNode root) {
		if (root == null)
			return;
		preOrder(root.left);
		System.out.print(root.val + " ");
		preOrder(root.right);
	}

后续遍历

public void afterOrder(TreeNode root) {
		if (root == null)
			return;
		preOrder(root.left);
		preOrder(root.right);
		System.out.print(root.val + " ");
	}

2.非递归写法

先序遍历

public void preOrder1(TreeNode root) {
		Stack<TreeNode> stack=new Stack<>();
		TreeNode currNode=root;
		if(currNode!=null) {
			stack.push(currNode);//根节点入栈
			while(!stack.isEmpty()) {
				currNode=stack.pop();//弹出根节点
				System.out.print(currNode.val+" ");
				if(currNode.right!=null) {//右节点先压入栈
					stack.push(currNode.right);
				}
				if(currNode.left!=null) {
					stack.push(currNode.left);
				}
			}
		}
	}

中序遍历

public void inOrder1(TreeNode root) {
		Stack<TreeNode> stack=new Stack<>();
		TreeNode currNode=root;
		while(currNode!=null||!stack.isEmpty()) {
			//先访问左节点,压入左节点
			while(currNode!=null) {
				stack.push(currNode);
				currNode=currNode.left;
			}
			if(!stack.isEmpty()) {
				currNode=stack.pop();//弹出左节点
				System.out.print(currNode.val+" ");
				currNode=currNode.right;//开始压入右节点
			}
		}
	}

后续遍历

public void afterOrder1(TreeNode root) {
		Stack<TreeNode> stack1=new Stack<>();
		Stack<TreeNode> stack2=new Stack<>();
		TreeNode currNode=root;
		while(currNode!=null||!stack1.isEmpty()) {
			while(currNode!=null) {
				//使用两个栈在stack2中按照左右顺序入栈
				stack1.push(currNode);
				stack2.push(currNode);
				currNode=currNode.right;
			}
			if(!stack1.isEmpty()) {
				currNode=stack1.pop();//弹出左节点
				currNode=currNode.left;
			}
		}
		while(!stack2.isEmpty()) {
			currNode=stack2.pop();
			System.out.print(currNode.val+" ");
		}
	}

3.层序遍历

public void levelOrder(TreeNode root) {
		if (root == null)
			return;
		Queue<TreeNode> q = new LinkedList<>();// 定义一个队列
		q.offer(root);// 存入根节点
		while (!q.isEmpty()) {
			TreeNode temp = q.poll();// 弹出根节点
			System.out.print(temp.val + " ");// 输出根节点
			if (temp.left != null) {// 找到根节点下的左右节点并存入队列
				q.offer(temp.left);
			}
			if (temp.right != null) {
				q.offer(temp.right);
			}
		}
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值