1038. 从二叉搜索树到更大和树
解题思路
- 改造中序遍历算法
- 先遍历右子树 然后累加当前节点的值 再遍历左子树
/*** 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 {public TreeNode bstToGst(TreeNode root) {// 改造中序遍历算法traverse(root);return root;}int sum = 0;public void traverse(TreeNode root){if(root == null){return;}traverse(root.right);sum += root.val;root.val = sum;// 比他大的所有数字之和traverse(root.left);}
}