《演算法筆記》7. 二叉樹基本演算法整理

Inky發表於2020-07-28

1 二叉樹基本演算法

1.1 二叉樹的遍歷

1.1.1 二叉樹節點定義

    Class Node{
        // 節點的值型別
        V value;
        // 二叉樹的左孩子指標
        Node left;
        // 二叉樹的右孩子指標
        Node right;
    }

1.1.2 遞迴實現先序中序後序遍歷

先序:任何子樹的處理順序都是,先頭結點,再左子樹,再右子樹。先處理頭結點

中序:任何子樹的處理順序都是,先左子樹,再頭結點,再右子樹。中間處理頭結點

後序:任何子樹的處理順序都是,先左子樹,再右子樹,再頭結點。最後處理頭結點

對於下面的一棵樹:

graph TD
1-->2
1-->3
2-->4
2-->5
3-->6
3-->7

1、 先序遍歷為:1 2 4 5 3 6 7

2、 中序遍歷為:4 2 5 1 6 3 7

3、 後序遍歷為:4 5 2 6 7 3 1

package class07;

public class Code01_RecursiveTraversalBT {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int v) {
			value = v;
		}
	}

	public static void f(Node head) {
		if (head == null) {
			return;
		}
		// 1 此處列印等於先序
		f(head.left);
		// 2 此處列印等於中序
		f(head.right);
		// 3 此處列印等於後序
	}

	// 先序列印所有節點
	public static void pre(Node head) {
		if (head == null) {
			return;
		}
		// 列印頭
		System.out.println(head.value);
		// 遞迴列印左子樹
		pre(head.left);
		// 遞迴列印右子樹
		pre(head.right);
	}

        // 中序遍歷
	public static void in(Node head) {
		if (head == null) {
			return;
		}
		in(head.left);
		System.out.println(head.value);
		in(head.right);
	}

        // 後序遍歷
	public static void pos(Node head) {
		if (head == null) {
			return;
		}
		pos(head.left);
		pos(head.right);
		System.out.println(head.value);
	}

	public static void main(String[] args) {
		Node head = new Node(1);
		head.left = new Node(2);
		head.right = new Node(3);
		head.left.left = new Node(4);
		head.left.right = new Node(5);
		head.right.left = new Node(6);
		head.right.right = new Node(7);

		pre(head);
		System.out.println("========");
		in(head);
		System.out.println("========");
		pos(head);
		System.out.println("========");

	}

}

結論:對於樹的遞迴,每個節點實質上會到達三次,例如上文的樹結構,對於f函式,我們傳入頭結點,再呼叫左樹再呼叫右樹。實質上經過的路徑為1 2 4 4 4 2 5 5 5 2 1 3 6 6 6 3 7 7 7 3 1。我們在每個節點三次返回的基礎上,第一次到達該節點就列印,就是先序,第二次到達該節點列印就是中序,第三次到達該節點就是後序。

所以先序中序後序,只是我們的遞迴順序加工出來的結果!

1.1.3 非遞迴實現先序中序後序遍歷

思路:由於任何遞迴可以改為非遞迴,我們可以使用壓棧來實現。用先序實現的步驟,其他類似:

步驟一,把節點壓入棧中,彈出就列印

步驟二,如果有右孩子先壓入右孩子

步驟三,如果有左孩子壓入左孩子

package class07;

import java.util.Stack;

public class Code02_UnRecursiveTraversalBT {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int v) {
			value = v;
		}
	}

        // 非遞迴先序
	public static void pre(Node head) {
		System.out.print("pre-order: ");
		if (head != null) {
			Stack<Node> stack = new Stack<Node>();
			stack.add(head);
			while (!stack.isEmpty()) {
			        // 彈出就列印
				head = stack.pop();
				System.out.print(head.value + " ");
				// 右孩子不為空,壓右
				if (head.right != null) {
					stack.push(head.right);
				}
				// 左孩子不為空,壓左
				if (head.left != null) {
					stack.push(head.left);
				}
			}
		}
		System.out.println();
	}

        // 非遞迴中序
	public static void in(Node head) {
		System.out.print("in-order: ");
		if (head != null) {
			Stack<Node> stack = new Stack<Node>();
			while (!stack.isEmpty() || head != null) {
			        // 整條左邊界依次入棧
				if (head != null) {
					stack.push(head);
					head = head.left;
				// 左邊界到頭彈出一個列印,來到該節點右節點,再把該節點的左樹以此進棧
				} else {
					head = stack.pop();
					System.out.print(head.value + " ");
					head = head.right;
				}
			}
		}
		System.out.println();
	}

        // 非遞迴後序
	public static void pos1(Node head) {
		System.out.print("pos-order: ");
		if (head != null) {
			Stack<Node> s1 = new Stack<Node>();
			// 輔助棧
			Stack<Node> s2 = new Stack<Node>();
			s1.push(head);
			while (!s1.isEmpty()) {
				head = s1.pop();
				s2.push(head);
				if (head.left != null) {
					s1.push(head.left);
				}
				if (head.right != null) {
					s1.push(head.right);
				}
			}
			while (!s2.isEmpty()) {
				System.out.print(s2.pop().value + " ");
			}
		}
		System.out.println();
	}

        // 非遞迴後序2:用一個棧實現後序遍歷,比較有技巧
	public static void pos2(Node h) {
		System.out.print("pos-order: ");
		if (h != null) {
			Stack<Node> stack = new Stack<Node>();
			stack.push(h);
			Node c = null;
			while (!stack.isEmpty()) {
				c = stack.peek();
				if (c.left != null && h != c.left && h != c.right) {
					stack.push(c.left);
				} else if (c.right != null && h != c.right) {
					stack.push(c.right);
				} else {
					System.out.print(stack.pop().value + " ");
					h = c;
				}
			}
		}
		System.out.println();
	}

	public static void main(String[] args) {
		Node head = new Node(1);
		head.left = new Node(2);
		head.right = new Node(3);
		head.left.left = new Node(4);
		head.left.right = new Node(5);
		head.right.left = new Node(6);
		head.right.right = new Node(7);

		pre(head);
		System.out.println("========");
		in(head);
		System.out.println("========");
		pos1(head);
		System.out.println("========");
		pos2(head);
		System.out.println("========");
	}

}

1.1.4 二叉樹按層遍歷

1、 其實就是寬度優先遍歷,用佇列

2、 可以通過設定flag變數的方式,來發現某一層的結束

按層列印輸出二叉樹

package class07;

import java.util.LinkedList;
import java.util.Queue;

public class Code03_LevelTraversalBT {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int v) {
			value = v;
		}
	}

	public static void level(Node head) {
		if (head == null) {
			return;
		}
		// 準備一個輔助佇列
		Queue<Node> queue = new LinkedList<>();
		// 加入頭結點
		queue.add(head);
		// 佇列不為空出隊列印,把當前節點的左右孩子加入佇列
		while (!queue.isEmpty()) {
			Node cur = queue.poll();
			System.out.println(cur.value);
			if (cur.left != null) {
				queue.add(cur.left);
			}
			if (cur.right != null) {
				queue.add(cur.right);
			}
		}
	}

	public static void main(String[] args) {
		Node head = new Node(1);
		head.left = new Node(2);
		head.right = new Node(3);
		head.left.left = new Node(4);
		head.left.right = new Node(5);
		head.right.left = new Node(6);
		head.right.right = new Node(7);

		level(head);
		System.out.println("========");
	}

}

找到二叉樹的最大寬度

package class07;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

public class Code06_TreeMaxWidth {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}

        // 方法1使用map
	public static int maxWidthUseMap(Node head) {
		if (head == null) {
			return 0;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.add(head);
		// key(節點) 在 哪一層,value
		HashMap<Node, Integer> levelMap = new HashMap<>();
		// head在第一層
		levelMap.put(head, 1);
		// 當前你正在統計哪一層的寬度
		int curLevel = 1; 
		// 當前層curLevel層,寬度目前是多少
		int curLevelNodes = 0; 
		// 用來儲存所有層的最大值,也就是最大寬度
		int max = 0;
		while (!queue.isEmpty()) {
			Node cur = queue.poll();
			int curNodeLevel = levelMap.get(cur);
			// 當前節點的左孩子不為空,佇列加入左孩子,層數在之前層上加1
			if (cur.left != null) {
				levelMap.put(cur.left, curNodeLevel + 1);
				queue.add(cur.left);
			}
			// 當前節點的右孩子不為空,佇列加入右孩子,層數也變為當前節點的層數加1
			if (cur.right != null) {
				levelMap.put(cur.right, curNodeLevel + 1);
				queue.add(cur.right);
			}
			// 當前層等於正在統計的層數,不結算
			if (curNodeLevel == curLevel) {
				curLevelNodes++;
			} else {
			    // 新的一層,需要結算
			    // 得到目前為止的最大寬度
				max = Math.max(max, curLevelNodes);
				curLevel++;
				// 結算後,當前層節點數設定為1
				curLevelNodes = 1;
			}
		}
		// 由於最後一層,沒有新的一層去結算,所以這裡單獨結算最後一層
		max = Math.max(max, curLevelNodes);
		return max;
	}

        // 方法2不使用map
	public static int maxWidthNoMap(Node head) {
		if (head == null) {
			return 0;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.add(head);
		// 當前層,最右節點是誰,初始head的就是本身
		Node curEnd = head; 
		// 如果有下一層,下一層最右節點是誰
		Node nextEnd = null; 
		// 全域性最大寬度
		int max = 0;
		// 當前層的節點數
		int curLevelNodes = 0; 
		while (!queue.isEmpty()) {
			Node cur = queue.poll();
			// 左邊不等於空,加入左
			if (cur.left != null) {
				queue.add(cur.left);
				// 孩子的最右節點暫時為左節點
				nextEnd = cur.left;
			}
			// 右邊不等於空,加入右
			if (cur.right != null) {
				queue.add(cur.right);
				// 如果有右節點,孩子層的最右要更新為右節點
				nextEnd = cur.right;
			}
			// 由於最開始彈出當前節點,那麼該層的節點數加一
			curLevelNodes++;
			// 當前節點是當前層最右的節點,進行結算
			if (cur == curEnd) {
			    // 當前層的節點和max進行比較,計算當前最大的max
				max = Math.max(max, curLevelNodes);
				// 即將進入下一層,重置下一層節點為0個節點
				curLevelNodes = 0;
				// 當前層的最右,直接更新為找出來的下一層最右
				curEnd = nextEnd;
			}
		}
		return max;
	}

	// for test
	public static Node generateRandomBST(int maxLevel, int maxValue) {
		return generate(1, maxLevel, maxValue);
	}

	// for test
	public static Node generate(int level, int maxLevel, int maxValue) {
		if (level > maxLevel || Math.random() < 0.5) {
			return null;
		}
		Node head = new Node((int) (Math.random() * maxValue));
		head.left = generate(level + 1, maxLevel, maxValue);
		head.right = generate(level + 1, maxLevel, maxValue);
		return head;
	}

	public static void main(String[] args) {
		int maxLevel = 10;
		int maxValue = 100;
		int testTimes = 1000000;
		for (int i = 0; i < testTimes; i++) {
			Node head = generateRandomBST(maxLevel, maxValue);
			if (maxWidthUseMap(head) != maxWidthNoMap(head)) {
				System.out.println("Oops!");
			}
		}
		System.out.println("finish!");

	}

}

1.2 二叉樹的序列化和反序列化

1、 可以用先序或者中序或者後序或者按層遍歷,來實現二叉樹的序列化

2、 用了什麼方式的序列化,就用什麼方式的反序列化

由於如果樹上的節點值相同,那麼序列化看不出來該樹的結構,所以我們的序列化要加上空間結構的標識,空節點補全的方式。

package class07;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class Code04_SerializeAndReconstructTree {
    /*
     * 二叉樹可以通過先序、後序或者按層遍歷的方式序列化和反序列化,
     * 以下程式碼全部實現了。
     * 但是,二叉樹無法通過中序遍歷的方式實現序列化和反序列化
     * 因為不同的兩棵樹,可能得到同樣的中序序列,即便補了空位置也可能一樣。
     * 比如如下兩棵樹
     *         __2
     *        /
     *       1
     *       和
     *       1__
     *          \
     *           2
     * 補足空位置的中序遍歷結果都是{ null, 1, null, 2, null}
     *       
     * */
	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}

        // 先序序列化
	public static Queue<String> preSerial(Node head) {
		Queue<String> ans = new LinkedList<>();
		// 先序的序列化結果依次放入佇列中去
		pres(head, ans);
		return ans;
	}

	public static void pres(Node head, Queue<String> ans) {
		if (head == null) {
			ans.add(null);
		} else {
			ans.add(String.valueOf(head.value));
			pres(head.left, ans);
			pres(head.right, ans);
		}
	}

        // 中序有問題。見檔案開頭註釋
	public static Queue<String> inSerial(Node head) {
		Queue<String> ans = new LinkedList<>();
		ins(head, ans);
		return ans;
	}

	public static void ins(Node head, Queue<String> ans) {
		if (head == null) {
			ans.add(null);
		} else {
			ins(head.left, ans);
			ans.add(String.valueOf(head.value));
			ins(head.right, ans);
		}
	}

        // 後序序列化
	public static Queue<String> posSerial(Node head) {
		Queue<String> ans = new LinkedList<>();
		poss(head, ans);
		return ans;
	}

	public static void poss(Node head, Queue<String> ans) {
		if (head == null) {
			ans.add(null);
		} else {
			poss(head.left, ans);
			poss(head.right, ans);
			ans.add(String.valueOf(head.value));
		}
	}

        // 根據先序的結構,構建這顆樹
	public static Node buildByPreQueue(Queue<String> prelist) {
		if (prelist == null || prelist.size() == 0) {
			return null;
		}
		return preb(prelist);
	}

	public static Node preb(Queue<String> prelist) {
		String value = prelist.poll();
		// 如果頭節點是空的話,返回空
		if (value == null) {
			return null;
		}
		// 否則根據第一個值構建先序的頭結點
		Node head = new Node(Integer.valueOf(value));
		// 遞迴建立左樹
		head.left = preb(prelist);
		// 遞迴建立右樹
		head.right = preb(prelist);
		return head;
	}
    
        // 根據後序的結構,構建該樹
	public static Node buildByPosQueue(Queue<String> poslist) {
		if (poslist == null || poslist.size() == 0) {
			return null;
		}
		// 左右中  ->  stack(中右左)
		Stack<String> stack = new Stack<>();
		while (!poslist.isEmpty()) {
			stack.push(poslist.poll());
		}
		return posb(stack);
	}

	public static Node posb(Stack<String> posstack) {
		String value = posstack.pop();
		if (value == null) {
			return null;
		}
		Node head = new Node(Integer.valueOf(value));
		head.right = posb(posstack);
		head.left = posb(posstack);
		return head;
	}

        // 按層序列化,整體上就是寬度優先遍歷
	public static Queue<String> levelSerial(Node head) {
	        // 序列化結果
		Queue<String> ans = new LinkedList<>();
		if (head == null) {
			ans.add(null);
		} else {
		        // 加入一個節點的時候,把該節點的值加入
			ans.add(String.valueOf(head.value));
			// 輔助佇列
			Queue<Node> queue = new LinkedList<Node>();
			queue.add(head);
			while (!queue.isEmpty()) {
				head = queue.poll();
				// 左孩子不為空,即序列化,也加入佇列
				if (head.left != null) {
            	ans.add(String.valueOf(head.left.value));
					queue.add(head.left);
				// 左孩子等於空,只序列化,不加入佇列
				} else {
					ans.add(null);
				}
				if (head.right != null) {
					ans.add(String.valueOf(head.right.value));
					queue.add(head.right);
				} else {
					ans.add(null);
				}
			}
		}
		return ans;
	}

        // 按層反序列化
	public static Node buildByLevelQueue(Queue<String> levelList) {
		if (levelList == null || levelList.size() == 0) {
			return null;
		}
		Node head = generateNode(levelList.poll());
		Queue<Node> queue = new LinkedList<Node>();
		if (head != null) {
			queue.add(head);
		}
		Node node = null;
		while (!queue.isEmpty()) {
			node = queue.poll();
			// 不管左右孩子是否為空,都要加節點
			node.left = generateNode(levelList.poll());
			node.right = generateNode(levelList.poll());
			// 左孩子不為空,佇列加左,為建下一層做準備
			if (node.left != null) {
				queue.add(node.left);
			}
			// 右孩子不為空,佇列加右,為建下一層做準備
			if (node.right != null) {
				queue.add(node.right);
			}
		}
		return head;
	}

	public static Node generateNode(String val) {
		if (val == null) {
			return null;
		}
		return new Node(Integer.valueOf(val));
	}

	// for test
	public static Node generateRandomBST(int maxLevel, int maxValue) {
		return generate(1, maxLevel, maxValue);
	}

	// for test
	public static Node generate(int level, int maxLevel, int maxValue) {
		if (level > maxLevel || Math.random() < 0.5) {
			return null;
		}
		Node head = new Node((int) (Math.random() * maxValue));
		head.left = generate(level + 1, maxLevel, maxValue);
		head.right = generate(level + 1, maxLevel, maxValue);
		return head;
	}

	// for test
	public static boolean isSameValueStructure(Node head1, Node head2) {
		if (head1 == null && head2 != null) {
			return false;
		}
		if (head1 != null && head2 == null) {
			return false;
		}
		if (head1 == null && head2 == null) {
			return true;
		}
		if (head1.value != head2.value) {
			return false;
		}
		return isSameValueStructure(head1.left, head2.left) && isSameValueStructure(head1.right, head2.right);
	}

	// for test
	public static void printTree(Node head) {
		System.out.println("Binary Tree:");
		printInOrder(head, 0, "H", 17);
		System.out.println();
	}

	public static void printInOrder(Node head, int height, String to, int len) {
		if (head == null) {
			return;
		}
		printInOrder(head.right, height + 1, "v", len);
		String val = to + head.value + to;
		int lenM = val.length();
		int lenL = (len - lenM) / 2;
		int lenR = len - lenM - lenL;
		val = getSpace(lenL) + val + getSpace(lenR);
		System.out.println(getSpace(height * len) + val);
		printInOrder(head.left, height + 1, "^", len);
	}

	public static String getSpace(int num) {
		String space = " ";
		StringBuffer buf = new StringBuffer("");
		for (int i = 0; i < num; i++) {
			buf.append(space);
		}
		return buf.toString();
	}

	public static void main(String[] args) {
		int maxLevel = 5;
		int maxValue = 100;
		int testTimes = 1000000;
		System.out.println("test begin");
		for (int i = 0; i < testTimes; i++) {
			Node head = generateRandomBST(maxLevel, maxValue);
			Queue<String> pre = preSerial(head);
			Queue<String> pos = posSerial(head);
			Queue<String> level = levelSerial(head);
			Node preBuild = buildByPreQueue(pre);
			Node posBuild = buildByPosQueue(pos);
			Node levelBuild = buildByLevelQueue(level);
			if (!isSameValueStructure(preBuild, posBuild) || !isSameValueStructure(posBuild, levelBuild)) {
				System.out.println("Oops!");
			}
		}
		System.out.println("test finish!");
		
	}
}

1.3 直觀列印一顆二叉樹

如何設計一個列印整顆數的列印函式,簡單起見,我們躺著列印,正常的樹我們順時針旋轉90°即可

package class07;

public class Code05_PrintBinaryTree {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}

	public static void printTree(Node head) {
		System.out.println("Binary Tree:");
		// 列印函式,先傳入頭結點
		printInOrder(head, 0, "H", 17);
		System.out.println();
	}

        // head表示當前傳入節點
        // height當前節點所在的高度
        // to表示當前節點的指向資訊
        // len表示列印當前值填充到多少位當成一個完整的值
	public static void printInOrder(Node head, int height, String to, int len) {
		if (head == null) {
			return;
		}
		// 遞迴右樹,右樹向下指
		printInOrder(head.right, height + 1, "v", len);
		/**
		* 列印自己的值
		* val 表示值內容
		**/
		String val = to + head.value + to;
		int lenM = val.length();
		// 按照len算該值左側需要填充多少空格
		int lenL = (len - lenM) / 2;
		// 按照len算該值右側需要填充多少空格
		int lenR = len - lenM - lenL;
		// 實際值加上左右佔位,表示每個值包括佔位之後大小
		val = getSpace(lenL) + val + getSpace(lenR);
		System.out.println(getSpace(height * len) + val);
		// 遞迴左樹,左樹向上指
		printInOrder(head.left, height + 1, "^", len);
	}

        // 根據height*len補空格
	public static String getSpace(int num) {
		String space = " ";
		StringBuffer buf = new StringBuffer("");
		for (int i = 0; i < num; i++) {
			buf.append(space);
		}
		return buf.toString();
	}

	public static void main(String[] args) {
		Node head = new Node(1);
		head.left = new Node(-222222222);
		head.right = new Node(3);
		head.left.left = new Node(Integer.MIN_VALUE);
		head.right.left = new Node(55555555);
		head.right.right = new Node(66);
		head.left.left.right = new Node(777);
		printTree(head);

		head = new Node(1);
		head.left = new Node(2);
		head.right = new Node(3);
		head.left.left = new Node(4);
		head.right.left = new Node(5);
		head.right.right = new Node(6);
		head.left.left.right = new Node(7);
		printTree(head);

		head = new Node(1);
		head.left = new Node(1);
		head.right = new Node(1);
		head.left.left = new Node(1);
		head.right.left = new Node(1);
		head.right.right = new Node(1);
		head.left.left.right = new Node(1);
		printTree(head);

	}

}

1.4 題目實戰

1.4.1 題目一:返回二叉樹的後繼節點

題目描述:二叉樹的結構定義如下:

Class Node {
    V value;
    Node left;
    Node right;
    // 指向父親節點
    Node parent;
}

給你二叉樹中的某個節點,返回該節點的後繼節點。後繼節點表示一顆二叉樹中,在中序遍歷的序列中,一個個節點的下一個節點是誰。

方法一,通常解法思路:由於我們的節點有指向父節點的指標,而整顆二叉樹的頭結點的父節點為null。那麼我們可以找到整棵樹的頭結點,然後中序遍歷,再找到給定節點的下一個節點,就是該節點的後續節點。

方法二,考慮一個節點和其後繼節點的結構之間的關係:

如果一個節點x有右樹,那麼其後繼節點就是右樹最左的節點。

如果x沒有右樹,往上找父親節點。如果x是其父親的右孩子繼續往上找,如果某節點是其父親節點的左孩子,那麼該節點的父親就是x的後繼節點

即如果某節點左樹的最右節點是x,那麼該節點是x的後繼

如果找父節點,一直找到null都不滿足,那麼該節點是整棵樹的最右節點,沒有後繼

package class07;

public class Code07_SuccessorNode {

	public static class Node {
		public int value;
		public Node left;
		public Node right;
		public Node parent;

		public Node(int data) {
			this.value = data;
		}
	}

        // 給定節點,返回後繼
	public static Node getSuccessorNode(Node node) {
		if (node == null) {
			return node;
		}
		if (node.right != null) {
			return getLeftMost(node.right);
		// 無右子樹
		} else { 
			Node parent = node.parent;
			// 當前節點是其父親節點右孩子,繼續
			while (parent != null && parent.right == node) { 
				node = parent;
				parent = node.parent;
			}
			return parent;
		}
	}

        // 找右樹上的最左節點
	public static Node getLeftMost(Node node) {
		if (node == null) {
			return node;
		}
		while (node.left != null) {
			node = node.left;
		}
		return node;
	}

	public static void main(String[] args) {
		Node head = new Node(6);
		head.parent = null;
		head.left = new Node(3);
		head.left.parent = head;
		head.left.left = new Node(1);
		head.left.left.parent = head.left;
		head.left.left.right = new Node(2);
		head.left.left.right.parent = head.left.left;
		head.left.right = new Node(4);
		head.left.right.parent = head.left;
		head.left.right.right = new Node(5);
		head.left.right.right.parent = head.left.right;
		head.right = new Node(9);
		head.right.parent = head;
		head.right.left = new Node(8);
		head.right.left.parent = head.right;
		head.right.left.left = new Node(7);
		head.right.left.left.parent = head.right.left;
		head.right.right = new Node(10);
		head.right.right.parent = head.right;

		Node test = head.left.left;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.left.left.right;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.left;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.left.right;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.left.right.right;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.right.left.left;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.right.left;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.right;
		System.out.println(test.value + " next: " + getSuccessorNode(test).value);
		test = head.right.right; // 10's next is null
		System.out.println(test.value + " next: " + getSuccessorNode(test));
	}

}

後繼節點對應的是前驅結點,前驅結點的含義是中序遍歷,某節點的前一個節點

1.4.2 題目二:摺紙問題

請把一段紙條豎著放在桌子上,然後從紙條的下邊向上方對摺1次,壓出摺痕後展開。

此時摺痕是凹下去的,即摺痕凸起的方向指向紙條的背面。

如果從紙條的下邊向上方對摺2次,壓出摺痕後展開,此時有三條摺痕,從上到下依次是下摺痕,下摺痕和上摺痕。

給定一個輸入引數N,代表紙條都從下邊向上方連續對摺N次。請從上到下列印所有的摺痕的方向。

例如:N=1時,列印: down 。N=2時,列印:down down up

規律,大於一次後,每次摺痕出現的位置都是在上次摺痕的上方出現凹摺痕,下方出現凸摺痕。所以我們沒必要構建這顆樹,就可以用遞迴思維解決

對應的樹結構按層輸出為:
            1凹
    2凹             2凸
3凹     3凸     3凹     3凸
package class07;

public class Code08_PaperFolding {

	public static void printAllFolds(int N) {
	        // 先從頭結點出發,i初始值為1,切第一次的頭結點摺痕為凹摺痕
		printProcess(1, N, true);
	}

	// 遞迴過程,來到了某一個節點,
	// i是節點的層數,N一共的層數,down == true  凹    down == false 凸
	public static void printProcess(int i, int N, boolean down) {
		if (i > N) {
			return;
		}
		// 每個當前節點的左子節點是凹
		printProcess(i + 1, N, true);
		System.out.println(down ? "凹 " : "凸 ");
		// 每個當前節點的右子樹是凸
		printProcess(i + 1, N, false);
	}

	public static void main(String[] args) {
		int N = 3;
		// 折N次,列印所有凹凸分佈情況
		printAllFolds(N);
	}
}

相關文章