114. 二叉树展开为链表

很朴素的做法,有右子树就压入栈,然后处理左子树,如果左子树没有了,便取出栈中子树进行处理


class Solution {
public:
    void flatten(TreeNode* root) {
        stack<TreeNode*>s;
        TreeNode* temp = root;
        if(root == nullptr){
            return;
        }
      //循环开始没有判断右子树是否为空,导致根节点没有左子树时报错
        while(temp->left != nullptr ||temp->right != nullptr || !s.empty()){
         
            if(temp->right!=nullptr){
                s.push(temp->right);
            }
            if(temp->left!=nullptr){
               // cout<<"左"<<endl;
                temp->right = temp->left;
                temp->left = nullptr;
                temp = temp->right;
            }
            else{
                 // cout<<"右"<<endl;
                temp->right = s.top();
                s.pop();
                temp->left = nullptr;
                temp = temp->right;
             
            }
        }
       
    }
};

posted @ 2021-12-11 15:06  jozon  阅读(40)  评论(0)    收藏  举报