二叉樹先中後序遍歷(遞歸和非遞歸版本)

先序:

public void preOrder(TreeNode root) {
if(root == null){
return ;
}
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur=stack.pop();
System.out.print(cur.val);
if(cur.right != null){
stack.push(cur.right);
}
if(root.left!= null){
stack.push(cur.left);
		}
	}
}

二叉樹的中序遍歷

public void inOrder(TreeNode root) {
if(root == null){
return;}
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(true){
	while(cur!=null){
	stack.pop(cur);
	cur=cur.left;
	}
	if(stack.isEmpty()){
	break;
	}
	TreeNode top=stack.pop();
	System.out.print(top.val);
	cur=top.right;
	}
}

二叉樹的後序遍歷

public static void postOrder(TreeNode root) {
if(root == null){
return ;}
TreeNode cur=root;
TreeNode prev=null;
while(true){
	while(cur!=null){
	stack.pop(cur);
	cur=cur.left;
	}
	if(stack.isEmpty()){
	break;
	}
	TreeNode top=stack.peek();
	if(top.right == null || top.right=prev){
		System.out.print(top.val);
		stack.pop;
		prev=pop;
	}else{
	cur=top.right;
		}
	}
}

也就是說二叉樹的三序遍歷,都是通過特殊的數據結構——棧來實現。
至於爲什麼這樣實現,有興趣的同學可以接下來試試。

遞歸版本
先序:

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 ;
}
inOrder(root.left);
System.out.print(root.val);
inOrder(root.right);
}

後序:

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

}
發佈了42 篇原創文章 · 獲贊 12 · 訪問量 3346
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章