`
cozilla
  • 浏览: 92564 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[Leetcode] Flatten Binary Tree to Linked List

 
阅读更多
Flatten Binary Tree to Linked ListOct 14 '127105 / 21371

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
Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

» Solve this problem

按照道理应该1更快,但是实际貌似差不多。

1和2的区别,主要是在对flat( right,xx)的处理上。

/**
 * Definition for binary tree
 * 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;
        TreeNode* tail;
        flat(root, tail);
    }
    
    void flat(TreeNode* cur, TreeNode* &tail) {
        
        if (cur->left == NULL && cur->right == NULL) {
            tail = cur;
            return;
        }
        
        if (cur->left != NULL) {
            TreeNode* lefttail;
            flat(cur->left, lefttail);
            lefttail->right = cur->right;
            cur->right = cur->left;
            cur->left = NULL;
            if (lefttail->right == NULL) 
                tail = lefttail;
            else {
                flat(lefttail->right, tail);
            }
        }
        else {
            flat(cur->right, tail);
        }
    }
};

 

 

/**
 * Definition for binary tree
 * 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;
        TreeNode* tail;
        flat(root, tail);
    }
    
    void flat(TreeNode* cur, TreeNode* &tail) {
        
        if (cur->left == NULL && cur->right == NULL) {
            tail = cur;
            return;
        }
        
        if (cur->left != NULL) {
            TreeNode* lefttail;
            flat(cur->left, lefttail);
            lefttail->right = cur->right;
            cur->right = cur->left;
            cur->left = NULL;
            
        }
        
        flat(cur->right, tail);
        
    }
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics