Title Description
Enter a binary search tree, the binary search tree converted into a doubly linked list sorted. Requirements can not create any new node, point to only adjust the tree node pointer.
method 1:
Ideas: the BST inorder traversal, the nodes stored in queue, the queue sequentially eject nodes, and follow the pop order to reconnect all the nodes.
1 import java.util.*; 2 class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 public class Solution { 14 public TreeNode Convert(TreeNode pRootOfTree) { 15 Queue<TreeNode> queue=new LinkedList<TreeNode>(); 16 inOrderToQueue(pRootOfTree,queue); 17 if (queue.isEmpty()) { 18 return pRootOfTree; 19 } 20 TreeNode head=queue.poll(); 21 TreeNode pre=head; 22 pre.left=null; 23 TreeNode cur=null; 24 while (!queue.isEmpty()) { 25 cur=queue.poll(); 26 pre.right=cur; 27 cur.left=pre; 28 pre=cur; 29 } 30 pre.right=null; 31 return head; 32 } 33 public void inOrderToQueue(TreeNode node,Queue<TreeNode> queue) { 34 if (node==null) { 35 return; 36 } 37 inOrderToQueue(node.left,queue); 38 queue.offer(node); 39 inOrderToQueue(node.right,queue); 40 } 41 }