《剑指Offer》36:二叉搜索树与双向链表
生活随笔
收集整理的這篇文章主要介紹了
《剑指Offer》36:二叉搜索树与双向链表
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
輸入一棵二叉搜索樹(shù),將該二叉搜索樹(shù)轉(zhuǎn)換成一個(gè)排序的雙向鏈表。要求不能創(chuàng)建任何新的節(jié)點(diǎn),只能調(diào)整樹(shù)中節(jié)點(diǎn)指針的指向。比如,輸入下圖中的二叉搜索樹(shù),輸出轉(zhuǎn)換之后的排序雙向鏈表。
二叉樹(shù)節(jié)點(diǎn)的定義如下:
public static class TreeNode {public int val;public TreeNode left;public TreeNode right;public TreeNode(int x) { val = x; } }分析
眾所周知,中序遍歷二叉搜索樹(shù)會(huì)得到有序的序列,我們目標(biāo)是在中序遍歷二叉搜索樹(shù)過(guò)程中,逐步將其轉(zhuǎn)換成有序的雙向鏈表。另外,將樹(shù)節(jié)點(diǎn)的左子樹(shù)指針轉(zhuǎn)換成雙向鏈表節(jié)點(diǎn)的前驅(qū)指針,而樹(shù)節(jié)點(diǎn)的右子樹(shù)指針轉(zhuǎn)換成雙向鏈表節(jié)點(diǎn)的后驅(qū)指針。
放碼
import com.lun.util.BinaryTree.TreeNode;public class ConvertBSTToLinkedList {private TreeNode last;//用于指向雙向鏈表的尾節(jié)點(diǎn)public TreeNode convert(TreeNode root) {convertNode(root);TreeNode head = last;while(head != null && head.left != null) {head = head.left;}return head;}private void convertNode(TreeNode node) {if(node == null) {return;}TreeNode current = node;if(current.left != null) {convertNode(current.left);}current.left = last;//1.執(zhí)行到這步,左子樹(shù)已經(jīng)轉(zhuǎn)換成有序雙向鏈表if(last != null) {last.right = current;//2.}last = current;//3.current轉(zhuǎn)換成有序雙向鏈表的新尾節(jié)點(diǎn)if(current.right != null) {convertNode(current.right);}}}測(cè)試
import org.junit.Assert; import org.junit.Test;import com.lun.util.BinaryTree; import com.lun.util.BinaryTree.TreeNode;public class ConvertBSTToLinkedListTest {@Testpublic void test() {ConvertBSTToLinkedList cbl = new ConvertBSTToLinkedList();TreeNode root = makeABST();TreeNode head = cbl.convert(root);Assert.assertEquals("4 -> 6 -> 8 -> 10 -> 12 -> 14 -> 16 -> \n" + "16 -> 14 -> 12 -> 10 -> 8 -> 6 -> 4 -> ", printList(head));}private TreeNode makeABST() {int[] array = {10, 6, 14, 4, 8, 12, 16};return BinaryTree.integerArray2BinarySearchTree(array);}private String printList(TreeNode head) {String result = "";TreeNode p = head;while(true) {result += (p.val + " -> ");if(p.right == null) {break;}p = p.right;}result += "\n";while(p != null) {result = result + p.val + " -> ";p = p.left;}return result;}}總結(jié)
以上是生活随笔為你收集整理的《剑指Offer》36:二叉搜索树与双向链表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 《Python Cookbook 3rd
- 下一篇: PaperNotes(9)-Learni