0
点赞
收藏
分享

微信扫一扫

非递归方式实现二叉树的先序遍历、后续遍历

程序员阿狸 2022-03-22 阅读 43

先序遍历:弹出就打印;如有右孩子压入右孩子;如有左孩子,压入左孩子

public static void pre(Node head) {
		System.out.print("pre-ord");
		if(head!=null) {
			Stack<Node> stack=new Stack<Node>();
			stack.add(head);
			while(!stack.isEmpty()) {
				head=stack.pop();
				System.out.print(head.value+"");
				if(head.right!=null) {
					stack.push(head.right);
				}
				if(head.left!=null) {
					stack.push(head.left);
				}
			}
		}
		System.out.println();
	}

后续遍历:准备两个栈,每一个头结点弹出后用另一个栈s2收集,先压左,再压右,最后s2弹出(即先序遍历改为先压左后压右,最后逆序输出)

public static void pos(Node head) {
		System.out.print("pos-order");
		if(head!=null) {
			Stack<Node> s1=new Stack<Node>();
			Stack<Node> s2=new Stack<Node>();
			s1.push(head);
			while(!s1.isEmpty()) {
				head=s1.pop();
				s2.push(head);
				if(head.left!=null) {
					s1.push(head.left);
				}
				if(head.right!=null) {
					s2.push(head.right);
				}
			}
			while(!s2.isEmpty()) {
				System.out.print(s2.pop().value+"");
			}
		}
		System.out.printil();
	}

举报

相关推荐

0 条评论