[leetcode]114. Flatten Binary Tree to Linked List將二叉樹展成一個連結串列
阿新 • • 發佈:2018-11-08
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
題目
將左子樹所形成的連結串列插入到root和root->right之間
思路
1 / 2(root) 假設當前root為2 / \ 3(p) 4
1 / 2(root) / \ 3(p)—— 4(root.right) p.right = root.right
1 / 2(root) / \ 3(root.right)- 4 root.right = root.left
1 / 2(root) \ 3(root.right)- 4 root.left - null
程式碼
1 class Solution { 2 public void flatten(TreeNode root) { 3 if (root == null) return; // 終止條件 4 // recursion 5 flatten(root.left); 6 flatten(root.right); 7 8 if (root.left == null) return; 9 10 // 三方合併,將左子樹所形成的連結串列插入到root和root->right之間11 TreeNode p = root.left; 12 while(p.right != null) { 13 p = p.right; //尋找左連結串列最後一個節點 14 } 15 p.right = root.right; 16 root.right = root.left; 17 root.left = null; 18 } 19 }