[LeetCode] 114. Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
1 \ 2 \ 3 \ 4 \ 5 \ 6
Hints:
Solution 1 (C++):
Solution 2 (Java):
Time complexity: O(n).
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Thought process:
Each node's right sub-tree is linked to its largest left child. So the idea is to recursively flatten a node's right sub-tree, then flatten its left sub-tree, and finally link the right sub-tree after the left sub-tree and move the sub-tree to the right.
The key point is to keep a prev pointer that points to the previously finished node, and attach it to the current node.
Solution 1 (C++):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: TreeNode* prev = NULL; public: void flatten(TreeNode* root) { if (root == NULL) { return; } flatten(root->right); flatten(root->left); root->right = prev; root->left = NULL; prev = root; } }; |
Solution 2 (Java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private TreeNode previous = null; public void flatten(TreeNode root) { if (root == null) { return; } flatten(root.right); flatten(root.left); root.right = previous; root.left = null; previous = root; } } |
Time complexity: O(n).
Comments
Post a Comment