二叉搜索树转换为链表
1 package com.algorithm; 2 3 public class BstALL { 4 //输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。 5 //要求不能创建任何新的结点,只能调整树中结点指针的指向 6 public TreeNode Convert(TreeNode pRootOfTree) { 7 if(pRootOfTree == null) 8 return null; 9 if(pRootOfTree.left == null && pRootOfTree.right == null) 10 return pRootOfTree; 11 //1、将左子树 构造成双链表,并返回链表头结点 12 TreeNode left = Convert(pRootOfTree.left); 13 TreeNode p = left; 14 //2、定位至左子树双链表最后一个节点 15 while(p!=null && p.right != null){ 16 p = p.right; 17 } 18 //3、如果左子树链表不为空,将当前root追加到左子树链表 19 if(left != null){ 20 p.right = pRootOfTree; 21 pRootOfTree.left = p; 22 } 23 //4、将右子树构成双链表,并返回链表头结点 24 TreeNode right = Convert(pRootOfTree.right); 25 //如果右子树链表不为空的话,将该链表追加到root节点之后 26 if(right != null){ 27 right.left = pRootOfTree; 28 pRootOfTree.right = right; 29 } 30 return left!=null?left:pRootOfTree; 31 } 32 public static void main(String[] args) { 33 TreeNode root = new TreeNode(10); 34 TreeNode rootleft = new TreeNode(6); 35 TreeNode rootright = new TreeNode(14); 36 root.left = rootleft; 37 root.right = rootright; 38 39 TreeNode root2 = new TreeNode(4); 40 TreeNode root3 = new TreeNode(8); 41 42 rootleft.left = root2; 43 rootleft.right = root3; 44 45 TreeNode root4 = new TreeNode(12); 46 TreeNode root5 = new TreeNode(16); 47 48 rootright.left = root4; 49 rootright.right = root5; 50 51 new BstALL().Convert(root); 52 53 } 54 }