美文网首页
recover-binary-search-tree

recover-binary-search-tree

作者: DaiMorph | 来源:发表于2019-05-03 19:56 被阅读0次

    中序遍历,保存节点和节点值,重新赋值
    https://www.cnblogs.com/grandyang/p/4298069.html
    O(1)复杂度用Mirror遍历

    class Solution {
    public:
        void recoverTree(TreeNode *root) {
            vector<TreeNode*>list;
            vector<int>vals;
            inorder(root,list,vals);
            sort(vals.begin(),vals.end());
            for(int i=0;i<list.size();i++)
                list[i]->val=vals[i];
        }
        void inorder(TreeNode*root,vector<TreeNode*>&list,vector<int>&vals)
        {
            if(!root)return;
            inorder(root->left,list,vals);
            list.push_back(root),vals.push_back(root->val);
            inorder(root->right,list,vals);
        }
    };
    

    相关文章

      网友评论

          本文标题:recover-binary-search-tree

          本文链接:https://www.haomeiwen.com/subject/lgyznqtx.html