runnig

[leetcode] 114 Flatten Binary Tree to Linked List

Feb 3rd, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. /*
  2. http://leetcode.com/onlinejudge#question_114
  3.  
  4. Given a binary tree, flatten it to a linked list in-place.
  5.  
  6. For example,
  7. Given
  8.  
  9.          1
  10.         / \
  11.        2   5
  12.       / \   \
  13.      3   4   6
  14. The flattened tree should look like:
  15.    1
  16.     \
  17.      2
  18.       \
  19.        3
  20.         \
  21.          4
  22.           \
  23.            5
  24.             \
  25.              6
  26. */           
  27. /**
  28.  * Definition for binary tree
  29.  * struct TreeNode {
  30.  *     int val;
  31.  *     TreeNode *left;
  32.  *     TreeNode *right;
  33.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  34.  * };
  35.  */
  36. class Solution {
  37. public:
  38.     typedef std::pair<TreeNode*, TreeNode*> nodepair_t;
  39.    
  40.     void connect(TreeNode * a, TreeNode * b)
  41.     {
  42.         if(a == b) { return; }
  43.         if(a) { a->right = b; }
  44.         if(b) { b->left = NULL; }        
  45.     }
  46.     nodepair_t flatten_impl(TreeNode *root)
  47.     {
  48.         if(!root) { return make_pair(root, root); }
  49.        
  50.         nodepair_t L = flatten_impl(root->left);
  51.         nodepair_t R = flatten_impl(root->right);
  52.         nodepair_t ret = make_pair(root, root);
  53.        
  54.         if(L.first)
  55.         {
  56.             connect(root, L.first);
  57.             ret.second = L.second;
  58.         }
  59.         if(R.first)
  60.         {
  61.             connect(ret.second, R.first);
  62.             ret.second = R.second;
  63.         }
  64.         root->left = NULL;
  65.         ret.second->right = NULL;
  66.         return ret;
  67.     }
  68.    
  69.     void flatten(TreeNode *root) {
  70.         flatten_impl(root);        
  71.     }
  72. };
Advertisement
Add Comment
Please, Sign In to add comment