1. 程式人生 > 實用技巧 >第九課:kubernetes儲存

第九課:kubernetes儲存

0、二叉樹結點的構造

1 public static class Node {
2         public int value;
3         public Node left;
4         public Node right;
5 
6         public Node(int data) {
7             this.value = data;
8         }
9 }

1、前序的非遞迴遍歷:

棧中每次彈出的當前結點後:列印彈出結點val值,有右先壓右,有左後壓左

 1 public static void preOrderUnRecur(Node head) {
2 System.out.print("pre-order: "); 3 if (head != null) { 4 Stack<Node> stack = new Stack<Node>(); 5 stack.add(head); 6 while (!stack.isEmpty()) { 7 head = stack.pop(); 8 System.out.print(head.value + " "); 9 if (head.right != null
) { 10 stack.push(head.right); 11 } 12 if (head.left != null) { 13 stack.push(head.left); 14 } 15 } 16 } 17 System.out.println(); 18 }

2、中序的非遞迴遍歷

當前結點不為空:壓棧,當前結點往左走

當前結點為空:彈棧,列印彈出棧的val值,當前結點往右走

 1 public static void
inOrderUnRecur(Node head) { 2 System.out.print("in-order: "); 3 if (head != null) { 4 Stack<Node> stack = new Stack<Node>(); 5 while (!stack.isEmpty() || head != null) { 6 if (head != null) { 7 stack.push(head); 8 head = head.left; 9 } else { 10 head = stack.pop(); 11 System.out.print(head.value + " "); 12 head = head.right; 13 } 14 } 15 } 16 System.out.println(); 17 }

3、後序的非遞迴遍歷

已知前序是:中--左--右,先轉換成:中--右--左,然後申請一個輔助棧顛倒成:左--右--中,接著遍歷列印輔助棧內結點的val值

那麼如何使用輔助棧顛倒成:左--右--中呢?

在彈棧的時候不列印元素而是將其壓入輔助棧

 1 public static void posOrderUnRecur(Node head) {
 2     System.out.print("pos-order: ");
 3     if (head != null) {
 4         Stack<Node> s1 = new Stack<Node>();
 5         Stack<Node> s2 = new Stack<Node>();
 6         s1.push(head);
 7         while (!s1.isEmpty()) {
 8             head = s1.pop();
 9             s2.push(head);
10             if (head.left != null) {
11                 s1.push(head.left);
12             }
13             if (head.right != null) {
14                 s1.push(head.right);
15             }
16         }
17         while (!s2.isEmpty()) {
18             System.out.print(s2.pop().value + " ");
19         }
20     }
21     System.out.println();
22 }