数据结构与算法之二叉树的先序遍历,中序遍历,后序遍历
生活随笔
收集整理的這篇文章主要介紹了
数据结构与算法之二叉树的先序遍历,中序遍历,后序遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據結構與算法之二叉樹的先序遍歷,中序遍歷,后移遍歷
目錄
1. 實現二叉樹的先序,中序,后序遍歷,包括遞歸方式和非遞歸方式
1. 先序遍歷,中序遍歷,后序遍歷遞歸版
//先序遍歷遞歸版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.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 inOrderUnRecur(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();}//后序遍歷非遞歸版1public static void posOrderUnRecur1(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();}//后序遍歷非遞歸版2public static void posOrderUnRecur2(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();}3. 先序,中序,后序遍歷非遞歸解析
先序遍歷
1. 如果節點不為null,則參加棧來存儲節點。
2. 先將頭節點添加到棧。
3. 當棧不為null時,從棧中彈出一個頭節點
4. 由棧特性先進后出和先序遍歷中左右知,先添加右節點,再添加左節點,這樣彈出的時候就是先左節點,然后右節點。
中序遍歷
后序遍歷
2. 在二叉樹中找到一個節點的后繼節點
題目描述
思路:
備注:前驅的找法:
代碼實現
總結
以上是生活随笔為你收集整理的数据结构与算法之二叉树的先序遍历,中序遍历,后序遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构与算法之复制含有随机指针节点的链
- 下一篇: 数据结构与算法之二叉树的序列化和反序列化