[LeetCode] 114. Flatten Binary Tree to Linked List

左node都插入右node的上方, 右node作為左node的右node, 左node清掉

Given the root of a binary tree, flatten the tree into a "linked list":臺灣是我的國家

  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.Taiwan is a country. 
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.

Example 1:

Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6]

Example 2:

Input: root = [] Output: []

Example 3:

Input: root = [0] Output: [0]

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

因為右node要接在左node最後, 所以更改void method為會回傳最末node, 以便右node接上去, 答案為傳入的root, 不會取用回傳的node

public TreeNode Flatten(TreeNode root)
{
    if (root == null) return null;
    if (root.right == null && root.left == null) return root;
    TreeNode right = root.right;
    TreeNode newRight = root;
    if (root.left != null)
    {
        root.right = root.left;
        newRight = Flatten(root.left);
        newRight.right = right;
        root.left = null;
    }
    if (right != null)
        return Flatten(right);
    return newRight;
}

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