《LeetCode力扣练习》代码随想录——二叉树(把二叉搜索树转换为累加树—Java)
刷题思路来源于 代码随想录
538. 把二叉搜索树转换为累加树
-
递归-中序遍历
/*** 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 pre = 0;public TreeNode convertBST(TreeNode root) {recursion(root);return root;}private void recursion(TreeNode root) {if (root == null) {return;}recursion(root.right);root.val = root.val + pre;pre = root.val;recursion(root.left);return;}}