题目链接
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int sum = 0; // 用于累加所有节点的值
public TreeNode convertBST(TreeNode root) {
traverse(root);
return root;
}
private void traverse(TreeNode root) {
if (root == null) {
return;
}
// 首先遍历右子树
traverse(root.right);
// 访问节点本身,并更新sum
sum += root.val;
root.val = sum;
// 最后遍历左子树
traverse(root.left);
}
}