题解:
递归三部曲:
1、确定递归函数参数和返回值
TreeNode* convertBST(TreeNode* root)
2、确定递归终止条件
遇空停止
3、确定单层递归逻辑
根据右中左的遍历顺序,针对中间结点 采用原结点值和前一个新树结点值累加的方式求得新结点值
/**
* 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 {
public:
TreeNode* pre = NULL;
TreeNode* convertBST(TreeNode* root) {
//新树的递增序列结点是原树递减序列结点
//原树递增为左中右 递减为右中左 故而遍历顺序为右中左 依次累加
if(root == NULL){
return NULL;
}
//单层递归逻辑
convertBST(root->right);
//累加
if(pre!=NULL){
root->val = pre->val+root->val;
}
pre = root;
convertBST(root->left);
return root;
}
};
迭代:反中序遍历
class Solution {
public:
TreeNode* pre = NULL;
TreeNode* convertBST(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = root;
while(cur!=NULL || !st.empty()){
if(cur!=NULL){
//往右走
st.push(cur);
cur = cur->right;
}else{
//开始处理结点
cur = st.top();
st.pop();
//结点值处理
if(pre!=NULL){
cur->val = pre->val+cur->val;
}
pre = cur;
cur = cur->left;
}
}
return root;
}
};