用遞歸方式實現二叉樹先序、中序和后序遍歷很簡單。
用遞歸方法解決的問題都能用非遞歸的方法實現。遞歸就是利用函數棧來保存信息,如果用自己申請的數據結構來代替函數棧,也可以實現相同的功能。
用非遞歸的方式實現二叉樹的先序遍歷(LeetCode144):
1、申請一個棧stack,然后將頭節點壓入stack中。
2、從stack中彈出棧頂節點,打印,再將其右孩子節點(不為空的話)先壓入stack中,最后將其左孩子節點(不為空的話)壓入stack中。
3、不斷重復步驟2,直到stack為空,全部過程結束。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 import java.util.*; 11 class Solution { 12 public List<Integer> preorderTraversal(TreeNode root) { 13 List<Integer> list=new ArrayList<Integer>(); 14 Stack<TreeNode> stack=new Stack<TreeNode>(); 15 if (root!=null) { 16 stack.push(root); 17 while(!stack.empty()) { 18 TreeNode tr=stack.pop(); 19 list.add(tr.val); 20 if(tr.right!=null) { 21 stack.push(tr.right); 22 } 23 if(tr.left!=null) { 24 stack.push(tr.left); 25 } 26 } 27 } 28 return list; 29 } 30 }
用非遞歸的方式實現二叉樹的中序遍歷(LeetCode94):
1、申請一個棧stack,初始時令cur=head
2、先把cur壓入棧中,依次把左邊界壓入棧中,即不停的令cur=cur.left,重復步驟2
3、不斷重復2,直到為null,從stack中彈出一個節點,記為node,打印node的值,並令cur=node.right,重復步驟2
4、當stack為空且cur為空時,整個過程停止。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> inorderTraversal(TreeNode head) { 12 List<Integer> list=new ArrayList<Integer>(); 13 Stack<TreeNode> stack=new Stack<TreeNode>(); 14 if (head!=null) { 15 while(head!=null||!stack.empty()) { 16 if(head!=null) { 17 stack.push(head); 18 head=head.left; 19 }else { 20 head=stack.pop(); 21 list.add(head.val); 22 head=head.right; 23 } 24 } 25 } 26 return list; 27 } 28 }
用非遞歸的方式實現二叉樹的后序遍歷(LeetCode145):
用非遞歸的方式實現后序遍歷有點麻煩。
1、申請一個棧s1,然后將頭節點壓入棧s1中。
2、從s1中彈出的節點記為cur,然后依次將cur的左孩子節點和右孩子節點壓入s1中。
3、在整個過程中,每一個從s1中彈出的節點都放進s2中。
4、不斷重復步驟2和步驟3,直到s1為空,過程停止。
5、從s2中依次彈出節點並打印,打印的順序就是后序遍歷的順序。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> postorderTraversal(TreeNode head) { 12 List<Integer> list=new ArrayList<Integer>(); 13 Stack<TreeNode> stack1=new Stack<TreeNode>(); 14 Stack<TreeNode> stack2=new Stack<TreeNode>(); 15 if (head!=null) { 16 stack1.push(head); 17 while(!stack1.empty()) { 18 head=stack1.pop(); 19 stack2.push(head); 20 if (head.left!=null) { 21 stack1.push(head.left); 22 } 23 if (head.right!=null) { 24 stack1.push(head.right); 25 } 26 } 27 while(!stack2.empty()) { 28 list.add(stack2.pop().val); 29 } 30 } 31 return list; 32 } 33 }
歡迎留言評論!!