论坛首页 编程语言技术论坛

[Leetcode] Flatten Binary Tree to Linked List

浏览 1431 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-09-09  
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