LeetCode_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

 思路; 展开后的树其实就是先根遍历的一个结果,不过注意是连接在右子树上。所以先做了一下先根遍历,并保存结果最后按照展开规则处理每个节点。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private :
  vector<TreeNode *> temp ;// record the preOrder result 
public:
   void preOrder(TreeNode *root){
    temp.push_back(root);
    if(root->left) preOrder(root->left);
    if(root->right) preOrder(root->right);
   
   }
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        temp.clear();
        if(root == NULL) return ;
        preOrder(root);
        for(int i = 0; i< temp.size()-1; i++)
         {
            temp[i]->right = temp[i+1];
            temp[i]->left = NULL ;
         }
       
    }
};
原文地址:https://www.cnblogs.com/graph/p/3194544.html