538. 把二叉搜索树转换为累加树

题解
这是一颗二叉搜索树,右子树的节点都比中间节点大,左子树的节点都比中间节点小。所以当转换成累加树时,右边的节点不变化,中间节点的值为 中+右的值,左边节点的值为左+中+右的值。使用全局变量递归进行反向中序遍历赋值即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
}
return root;
}
}

368

被折叠的 条评论
为什么被折叠?



