Tuesday, March 8, 2016

LeetCode Q114: Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.
For example,
Given
         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
Solution:
Using recursion, every time, link the right sub-tree to the deepest leaf node of the left sub-tree.

My code accepted in one pass, first time~!! Woo-Hoo~

/**
* 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 {
public:
void flatten(TreeNode* root){
if(root==NULL)
return;
if(root->left!=NULL)
flatten(root->left);
if(root->right!=NULL)
flatten(root->right);
TreeNode* tmpRight=root->right;
TreeNode* leftLeef;
if(root->left==NULL)
leftLeef=root;
else{
leftLeef=root->left;
while(leftLeef->right!=NULL){
leftLeef=leftLeef->right;
}
}
if(root->left!=NULL)
root->right=root->left;
root->left=NULL;
leftLeef->right=tmpRight;
}
};

No comments:

Post a Comment