Flatten Binary Tree to Linked ListOct 14 '12
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
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void flattenInt(TreeNode *root) { if (root->left) { flattenInt(root->left); TreeNode *temp=root->right; TreeNode *trav=root->left; /* Attach the right child of this node to * the rightmost node of the left child */ while (trav->right) trav = trav->right; root->right=root->left; trav->right=temp; root->left=NULL; } if (root->right) flattenInt(root->right); } public: void flatten(TreeNode *root) { if (!root) return; if (!root->left && !root->right) return; flattenInt(root); } }; /* Alternative Solution */ class Solution { void flattenInt(TreeNode *root, TreeNode **tail) { if (root) { TreeNode *right = root->right; TreeNode *left = root->left; if (*tail) { (*tail)->right = root; (*tail)->left = nullptr; } *tail = root; flattenInt(left, tail); flattenInt(right, tail); } } public: void flatten(TreeNode *root) { TreeNode *tail=nullptr; flattenInt(root, &tail); } };
No comments:
Post a Comment