1、题目描述:
2、题解:
方法一:反向中序遍历 递归
二叉搜索树的中序遍历是有序的,升序,那么我们就让“右根左”,也就是先递归右子树,然后处理根节点,然后递归左子树,这样就可以降序处理,然后定义一个变量sum_存储大于此刻值的所有节点的和。
Python实现:
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
#反向中序遍历,递归
if not root:
return root
sum_ = 0
def inorder(root):
nonlocal sum_
if not root:
return
inorder(root.right)
sum_ += root.val
root.val = sum_
inorder(root.left)
inorder(root)
return root
或者:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
# 倒序的中序遍历
if not root: return root
self.sum_ = 0
self.inorder(root)
return root
def inorder(self, root):
if not root:
return
self.inorder(root.right)
self.sum_ += root.val
root.val = self.sum_
self.inorder(root.left)
C++实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
if (root != nullptr){
convertBST(root->right);
sum += root->val;
root->val = sum;
convertBST(root->left);
}
return root;
}
};
方法2:反向中序遍历,迭代:
Python实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
#反向中序遍历,迭代
if not root:return root
res = root
total = 0
stack = []
while root or stack:
while root:
stack.append(root)
root = root.right
root = stack.pop()
root.val += total
total = root.val
root = root.left
return res
C++实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int sum = 0;
stack<TreeNode*> s;
TreeNode* res = root;
while (!s.empty() || root != nullptr){
while(root!=nullptr){
s.push(root);
root = root->right;
}
root = s.top();
s.pop();
// sum += root->val;
// root->val = sum;
root->val += sum;
sum = root->val;
root = root->left;
}
return res;
}
};
3、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)