二叉樹的遞歸遍歷和非遞歸遍歷
阿新 • • 發佈:2018-12-23
兩個 static bsp reorder sta class ror 後序 right
node 節點定義
public static class Node{ public int val; public Node left; public Node right; public Node(int val){ this.val = val; } }
遞歸前序遍歷:
public static void preOrder(Node head){ if (head != null ) { System.out.print(head.val); preOrder(head.left); preOrder(head.right); } }
非遞歸前序遍歷:先遍歷當前節點,再遍歷他的左子樹,再到右子樹。每個節點都保存著左右子樹的信息。
因為當前節點被彈出,所以必須要先保存他的右子樹。如果不將右子樹不壓棧的話,將會丟失信息。
public static void preOrder01(Node head) { if (head == null) { return; } Stack<Node> stack = new Stack<>(); stack.push(head);while(!stack.isEmpty()){ Node cur = stack.pop(); System.out.println(cur.val); if( cur.right != null ){ stack.push(cur.right); } if (cur.left != null ) { stack.push(cur.left); } } }
中序遞歸遍歷:
public static void midOrder(Node head){ if (head != null) { preOrder(head.left); System.out.print(head.val); preOrder(head.right); } }
中序非遞歸遍歷: 一直將他的左子樹壓棧。 一直到左子樹最左的節點。
public static void midOder01(Node head){ if (head == null){ return ; } Stack<Node> stack = new Stack<>(); stack.push(head); while(!stack.empty() || head != null){ if( head.left != null ){ stack.push(head.left); }else { head = stack.pop(); System.out.println(head.val); if (head.right != null) { stack.push(head.right); } } } }
後序遞歸遍歷:
public static void laterOrder(Node head){ if (head != null) { laterOrder(head.left); laterOrder(head.right); System.out.println(head.val); } }
後序非遞歸遍歷:
維護兩個棧,第一個棧遍歷樹的順序是 中右左
第二個 左右中。
public static void laterOrder1(Node head) { if (head == null) { return ; } Stack<Node> s1 = new Stack<>(); Stack<Node> s2 = new Stack<>(); s1.push(head); while(!s1.empty()){ head = s1.pop(); s2.push(head); if (head.right != null) { s1.push(head.left); } if (head.left != null) { s1.push(head.right); } } while(!s2.empty()){ head = s2.pop(); System.out.println(head.val); } }
二叉樹的遞歸遍歷和非遞歸遍歷