java数据结构与算法刷题-----LeetCode538. 把二叉搜索树转换为累加树

时间:2024-03-01 08:29:24
/** * 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 sum = 0;//指向逆中序遍历(右中左)前一个结点的val值 public TreeNode convertBST(TreeNode root) { if(root == null) return null; convertBST(root.right);//先右子树 sum += root.val;//累加,这就是当前结点的值,也是下一个结点的前驱值 root.val = sum;//然后保存累加后的值 convertBST(root.left);//然后左子树 return root; } }