思路
“反中根“遍历。从BST的最右节点开始遍历,然后记录当前的节点和,后面的每个节点只要加上这个和即可;在原树上修改。
将中根遍历的left和right访问顺序反过来,使用一个全局变量sum记录当前的和。整体思路类似分治算法。
代码
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: the new root
*/
int sum = 0;
public TreeNode convertBST(TreeNode root) {
// write your code here
dfs(root);
return root;
}
public void dfs(TreeNode root) {
if(root == null) return;
dfs(root.right);
root.val += sum;
sum = root.val;
dfs(root.left);
}
}
复杂度
时间复杂度O(n), 因为每个节点有且仅有一次访问
空间复杂度O(h)=O(logn), 因为用到了递归栈,栈的大小是树的高度。