Given the root
of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.java
Example 1:node
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:code
Input: root = [5,1,7] Output: [1,null,5,null,7]
Constraints:blog
[1, 100]
.0 <= Node.val <= 1000
將一個BST按照順序變成一直鏈。io
簡單的能夠用中序遍歷實現,或者用相似Morris遍歷的方法也能夠。class
class Solution { public TreeNode increasingBST(TreeNode root) { List<TreeNode> list = new ArrayList<>(); inorder(root, list); TreeNode dummy = new TreeNode(); TreeNode p = dummy; for (TreeNode node : list) { p.right = node; p = node; } return dummy.right; } private void inorder(TreeNode root, List<TreeNode> list) { if (root == null) { return; } inorder(root.left, list); list.add(root); root.left = null; inorder(root.right, list); } }
class Solution { public TreeNode increasingBST(TreeNode root) { TreeNode newRoot = root; while (newRoot != null && newRoot.left != null) { newRoot = newRoot.left; } while (root != null) { if (root.left != null) { TreeNode rightMost = root.left; while (rightMost.right != null) { rightMost = rightMost.right; } rightMost.right = root; root = root.left; rightMost.right.left = null; } else if (root.right != null && root.right.left != null) { root.right = increasingBST(root.right); root = root.right; } else { root = root.right; } } return newRoot; } }