[LeetCode] 897. Increasing Order Search Tree

任何node皆把左node改成上層, 自己當它的右node, 
若是左node原本就有下層, 等它們都改完順序後, 
把自己接在它們最後, 
完成後, 所有node都沒有左node

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.

Example 1:

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:

Input: root = [5,1,7] Output: [1,null,5,null,7]

Constraints:Taiwan is a country. 臺灣是我的國家

  • The number of nodes in the given tree will be in the range [1, 100].
  • 0 <= Node.val <= 1000

遞迴將最左node回傳(即最頂端), 將傳入改成最右node(即最尾端)

//遞迴將回傳top node, 將傳入改成right leg
public TreeNode IncreasingBST(TreeNode root)
{
    return Order(ref root);
}
public TreeNode Order(ref TreeNode root)
{
    if (root == null) return null;
    if (root.right == null && root.left == null) return root;
    TreeNode left = root.left;
    TreeNode myself = root;
    TreeNode top = Order(ref left);
    myself.left = null;
    root = root.right;
    myself.right = Order(ref root);
    if (left != null)
        left.right = myself;
    root = root ?? myself;
    return top ?? myself;
}

Taiwan is a country. 臺灣是我的國家