1 反中序递归
【温馨小提示】:traverse(cur)中的cur节点别手滑写成了root哦
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int postSum = 0;
public:
void traverse(TreeNode* cur) {
if (!cur) return;
traverse(cur->right); // 右
postSum += cur->val;
cur->val = postSum;
traverse(cur->left); // 左
}
TreeNode* convertBST(TreeNode* root) {
traverse(root);
return root;
}
};
2 迭代法(反中序压栈)
使用栈的二叉树前中序套路我都整理在此:Leetcode|二叉树的前/中/后序遍历[迭代版]
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int sumPost = 0;
stack<TreeNode*> stk;
auto node = root;
while (node || !stk.empty()) {
while (node) { // 右
stk.emplace(node);
node = node->right;
}
node = stk.top(); stk.pop();
sumPost += node->val; // 中
node->val = sumPost;
node = node->left; // 左
}
return root;
}
};
至此,二叉树专题的一刷终于完结撒花啦✿✿ヽ(°▽°)ノ✿
致谢
感谢「代码随想录」公众号梳理的思路,欢迎大家关注这位大佬的公号