leetcode--Flatten Binary Tree to Linked List

1.题目描述

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

2.解法分析

关键词:先序遍历 ,我的思路:

image

void flatten(TreeNode *root) {
       // Start typing your C/C++ solution below
       // DO NOT write int main() function
       if(!root)return; 
       vector<TreeNode *> st;
 
       TreeNode * cur=root;
       TreeNode * back=NULL;
       do
       {
           if(cur->right!=NULL)st.push_back(cur->right);
           if(cur->left!=NULL)
           {
               cur->right = cur->left;
               cur = cur->left;
           }
           else
           {
               if(!st.empty())
               {
                   back = st.back();st.pop_back();
                   cur->right = back;cur = back;
               }
           }    
       }while(!st.empty());
 }

但是程序运行结果却不对,不知为何,提示runtime error,但是在vs下调试又没有出现问题。

网传有一份代码,可以作为参考:

class Solution {
public:
void flatten(TreeNode *root) {
    if (!root) return;
 
    TreeNode* left = root->left;
    TreeNode* right = root->right;
 
    if (left) {
        root->right = left;
        root->left = NULL;
 
        TreeNode* rightmost = left;
        while(rightmost->right) {rightmost = rightmost->right;}
        rightmost->right = right; // point the right most to the original right child
    }
 
    flatten(root->right);        
}
};
原文地址:https://www.cnblogs.com/obama/p/3255183.html