二叉樹的前序中序後序遍歷-非遞歸-使用同一段代碼實現
阿新 • • 發佈:2018-09-20
非遞歸 傳統 前序遍歷 turn stack 實現 pan ++ tro
樹的遍歷通常使用遞歸,因為它的實現更簡單,代碼也更容易理解。
但在面試,或者特殊的情境中會使用到叠代算法(非遞歸)。
此時需要使用棧去模擬函數棧調用過程。
本文將給出一段代碼去實現這三種遍歷
相比於傳統的方式:前序遍歷,中序遍歷,後序遍歷,使用不同的方式代碼去實現,並且後續遍歷更為難理解一些
可拓展性更好(比如N叉樹的遍歷),也更容易理解
考慮,對於一個函數棧,它除了存儲了一些變量和指令,同時還存儲了當前執行位置。
對於樹的遍歷,無非為:t->val,t->left ,t->right 三個代碼的排列
因此,我們只需定義一個int類型的變量,用於記錄當前執行到哪一個代碼。
1 class TreeNodeWithIndex{ 2 public TreeNode node; 3 public int index=0; 4 public TreeNodeWithIndex(TreeNode n) { node = n; } 5 }
//0 pre ; 1 inorder ; 2 post 6 public IList<int> TreeTraversal(TreeNode root,int type) 7 { 8 var stack = newStack<TreeNodeWithIndex>(); 9 var ans = new List<int>(); 10 stack.Push(new TreeNodeWithIndex(root)); 11 while (stack.Count!=0) 12 { 13 var i = stack.Peek(); 14 if (i.index > 2 || i.node == null) { stack.Pop(); continue; } 15 if(type == i.index) ans.Add(i.node.val); 16 else 17 { 18 int tmp = type - i.index * 2; 19 if (tmp > 0 || tmp == -2) 20 stack.Push(new TreeNodeWithIndex(i.node.left)); 21 else 22 stack.Push(new TreeNodeWithIndex(i.node.right)); 23 } 24 i.index++; 25 } 26 return ans; 27 }
二叉樹的前序中序後序遍歷-非遞歸-使用同一段代碼實現