Leetcode第538&1038題 把二叉搜尋樹轉換為累加樹 C++解法
阿新 • • 發佈:2021-02-06
實際上還是中序遍歷,只是從右邊開始遍歷
class Solution {
public:
int s=0;
TreeNode* convertBST(TreeNode* root) {
if(!root)
return NULL;
convertBST(root->right);
s+=root->val;
root->val=s;
convertBST(root->left);
return root;
}
};
用迭代也做了下
class Solution {
public:
TreeNode* bstToGst(TreeNode* root) {
TreeNode* pmove=root;
stack<TreeNode*> s;
int cal=0;
while(!s.empty()||pmove)
{
while(pmove)
{s.push(pmove);
pmove=pmove->right;}
pmove= s.top();
s.pop();
cal+=pmove->val;
pmove->val=cal;
pmove=pmove->left;
}
return root;
}
};