题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
题解:中序遍历
private static TreeNode lastNode = null;
1 public TreeNode Convert(TreeNode pRootOfTree) { 2 inOrderConvert(pRootOfTree); 3 //寻找链表头节点 4 while (pRootOfTree != null && pRootOfTree.left != null){ 5 pRootOfTree = pRootOfTree.left; 6 } 7 return pRootOfTree; 8 } 9 public void inOrderConvert(TreeNode root) { 10 if (root == null) { 11 return; 12 } 13 inOrderConvert(root.left); 14 // 一个指针指向每次遍历到的节点,下一次中序遍历到的节点的前驱便是 15 // 此指针指向的节点,而此节点的后序是此时遍历到的节点 16 root.left = lastNode; 17 if (lastNode != null) { 18 lastNode.right = root; 19 } 20 lastNode = root; 21 inOrderConvert(root.right); 22 }
初始化树:
1 public static class TreeNode { 2 int val = 0; 3 TreeNode left = null; 4 TreeNode right = null; 5 public TreeNode(int val) { 6 this.val = val; 7 } 8 } 9 private static List<TreeNode> nodeList = null; 10 public static TreeNode createBinTree(int[] array) { 11 nodeList = new LinkedList<TreeNode>(); 12 // 将一个数组的值依次转换为TreeNode节点 13 for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) { 14 nodeList.add(new TreeNode(array[nodeIndex])); 15 } 16 // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树 17 for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) { 18 // 左孩子 19 nodeList.get(parentIndex).left = nodeList 20 .get(parentIndex * 2 + 1); 21 // 右孩子 22 nodeList.get(parentIndex).right = nodeList 23 .get(parentIndex * 2 + 2); 24 } 25 // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理 26 int lastParentIndex = array.length / 2 - 1; 27 // 左孩子 28 nodeList.get(lastParentIndex).left = nodeList 29 .get(lastParentIndex * 2 + 1); 30 // 右孩子,如果数组的长度为奇数才建立右孩子 31 if (array.length % 2 == 1) { 32 nodeList.get(lastParentIndex).right = nodeList 33 .get(lastParentIndex * 2 + 2); 34 } 35 return nodeList.get(0); 36 }
测试:
1 public static void main(String[] args) { 2 int[] tree = {10, 6, 14, 4, 8, 12, 16}; 3 TreeNode pRoot = createBinTree(tree); 4 TreeNode treeNode = Convert(pRoot); 5 System.out.print("From left to right are:"); 6 TreeNode tempLeft=treeNode; 7 while(tempLeft!=null){ 8 System.out.print(tempLeft.val+" "); 9 tempLeft=tempLeft.right; 10 } 11 System.out.println(); 12 System.out.print("From right to left are:"); 13 //找到最右节点 14 while (treeNode.right!=null){ 15 treeNode=treeNode.right; 16 } 17 while(treeNode!=null){ 18 System.out.print(treeNode.val+" "); 19 treeNode=treeNode.left; 20 } 21 } 22 输出: 23 From left to right are:4,6,8,10,12,14,16; 24 From right to left are:16,14,12,10,8,6,4;