538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
右中左遍历
/**
* 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 {
int num = 0;//全局变量用来记录上一次的和
public TreeNode convertBST(TreeNode root) {
if(root==null) return root;//递归终止条件
convertBST(root.right);//右
root.val = root.val + num;//中
num = root.val;
convertBST(root.left);//左
return root;
}
}