剑指offer面试题27:二叉搜索树与双向链表
生活随笔
收集整理的這篇文章主要介紹了
剑指offer面试题27:二叉搜索树与双向链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:輸入一顆二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能創建任何新的節點,只能調整樹中節點指針的指向。
由于二叉搜索樹是有序的,左子結點的值小于根節點的值,右子結點的值大于根節點的值。所以在把二叉搜索樹轉換成排序的雙向鏈表的時候要把左子樹中的最大值的右子樹指針指向根節點,把右子樹中的最小值的左子樹指針指向根節點。
由于先訪問根節點,因此要用中序遍歷的方式進行處理。
package Solution;public class No27ConvertBinarySearchTreeToLinkedList {static class BinaryTreeNode {int value;BinaryTreeNode left;BinaryTreeNode right;public BinaryTreeNode() {}public BinaryTreeNode(int value, BinaryTreeNode left,BinaryTreeNode right) {this.value = value;this.left = left;this.right = right;}}public static BinaryTreeNode convert(BinaryTreeNode root) {BinaryTreeNode lastNodeInList = null;lastNodeInList = convertToNode(root, lastNodeInList);BinaryTreeNode head = lastNodeInList;// 從尾節點返回頭結點while (head != null && head.left != null) {head = head.left;}printList(head);return head;}private static BinaryTreeNode convertToNode(BinaryTreeNode node,BinaryTreeNode lastNodeInList) {if (node == null)return null;BinaryTreeNode current = node;// 遞歸的處理左子樹if (current.left != null)lastNodeInList = convertToNode(current.left, lastNodeInList);// 使鏈表中的最后一個結點指向左子樹的最小的節點current.left = lastNodeInList;// 鏈表中的最后一個結點指向當前節點,當前節點就成了鏈表中的最后一個結點if (lastNodeInList != null)lastNodeInList.right = current;lastNodeInList = current;// 遞歸轉換右子樹if (current.right != null)lastNodeInList = convertToNode(current.right, lastNodeInList);return lastNodeInList;}public static void printList(BinaryTreeNode head) {while (head != null) {System.out.print(head.value + ",");head = head.right;}}// 中序遍歷二叉樹public static void printTree(BinaryTreeNode root) {if (root != null) {printTree(root.left);System.out.print(root.value + ",");printTree(root.right);}}public static void main(String[] args) {BinaryTreeNode node1 = new BinaryTreeNode();BinaryTreeNode node2 = new BinaryTreeNode();BinaryTreeNode node3 = new BinaryTreeNode();BinaryTreeNode node4 = new BinaryTreeNode();BinaryTreeNode node5 = new BinaryTreeNode();BinaryTreeNode node6 = new BinaryTreeNode();BinaryTreeNode node7 = new BinaryTreeNode();node7.value = 16;node6.value = 12;node5.value = 14;node5.left = node6;node5.right = node7;node3.value = 4;node4.value = 8;node2.value = 6;node2.left = node3;node2.right = node4;node1.value = 10;node1.left = node2;node1.right = node5;printTree(node1);System.out.println();System.out.println("=============打印鏈表================");convert(node1);} }?
轉載于:https://www.cnblogs.com/gl-developer/p/7296550.html
總結
以上是生活随笔為你收集整理的剑指offer面试题27:二叉搜索树与双向链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rabbitmq 入门demo
- 下一篇: TP5与TP3.X对比