二叉树的遍历(递归,非递归,Morris)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的遍历(递归,非递归,Morris)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
二叉樹的遍歷
目錄
1. 遞歸遍歷
遞歸版遍歷只要當(dāng)前節(jié)點不為null,就可以三次回到當(dāng)前節(jié)點。
public static void preOrderRecur(Node head) {if (head == null) {return;}System.out.print(head.value + " ");preOrderRecur(head.left);preOrderRecur(head.right);}public static void inOrderRecur(Node head) {if (head == null) {return;}inOrderRecur(head.left);System.out.print(head.value + " ");inOrderRecur(head.right);}public static void posOrderRecur(Node head) {if (head == null) {return;}posOrderRecur(head.left);posOrderRecur(head.right);System.out.print(head.value + " ");}2. 非遞歸遍歷
其中后序遍歷打印順序為左右中,由先序遍歷打印順序為中左右,所以可以對先序遍歷改進為中右左(改變添加順序),添加到另外一個棧中,最后遍歷打印就是左右中順序了。
public static void preOrderUnRecur(Node head) {System.out.println("pre-order: ");while (head != null) {Stack<Node> stack = new Stack<>();stack.push(head);while (!stack.isEmpty()) {Node node = stack.pop();System.out.println(node.value + " ");if (node.right != null) {stack.push(node.right);}if (node.left != null) {stack.push(node.left);}}}}public static void inOrderUnRecur(Node head) {System.out.print("in-order: ");if (head != null) {Stack<Node> stack = new Stack<>();while (!stack.isEmpty() || head != null) {if (head != null) {stack.push(head.left);head = head.left;} else {head = stack.pop();System.out.println(head.value + " ");head = head.right;}}}System.out.println();}public static void posOrderUnRecur1(Node head) {System.out.print("pos-order: ");if (head != null) {Stack<Node> s1 = new Stack<>();Stack<Node> s2 = new Stack<>();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();}3. Morris遍歷
Morris遍歷法,能以時間復(fù)雜度O(N),空間復(fù)雜度O(1)實現(xiàn)二叉樹的遍歷。
程序流程:
假設(shè)指針cur指向當(dāng)前節(jié)點,cur從頭結(jié)點開始。
假設(shè)二叉樹如下:
12 34 5 6 7則Morris遍歷順序為:1,2,4,2,5,1,3,6,3,7
Morris 遍歷代碼實現(xiàn):
public static void morrisIn(Node head) {if (head == null) {return;}Node cur = head;Node mostRight = null;while (cur != null) {mostRight = cur.left;if (mostRight != null) {while (mostRight.right != null && mostRight.right != cur) {mostRight = mostRight.right;}if (mostRight.right == null) {mostRight.right = cur;cur = cur.left;continue;} else {mostRight.right = null;}}cur = cur.right;}}特點:
實質(zhì):
Morris遍歷是利用左子樹最右節(jié)點的指針指向null或指向自己來標(biāo)記是第一次來到該節(jié)點還是第二次來到該節(jié)點。
Morris遍歷改先序遍歷
在以下兩種情況下打印節(jié)點:
Morris遍歷改中序遍歷
在以下兩種情況下打印節(jié)點:
Morris遍歷改后序遍歷
在以下兩種情況下打印節(jié)點:
總結(jié)
以上是生活随笔為你收集整理的二叉树的遍历(递归,非递归,Morris)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面经——Java基础
- 下一篇: LeetCode:输出整体轮廓线和最长子