2023.7.16
这道题利用中序遍历(右中左)的操作不断修改节点的值即刻,直接看代码:
class Solution {
public:TreeNode* convertBST(TreeNode* root) {stack<TreeNode*> stk;//前面的累加值int pre_value = 0;TreeNode* cur = root;if(cur == nullptr) return cur;//中序遍历(右中左)while(!stk.empty() || cur){while(cur){stk.push(cur);cur = cur->right; //右}cur = stk.top();stk.pop();pre_value += cur->val; //中cur->val = pre_value;cur = cur->left; //左}return root;}
};