【改造中序遍历算法】 LCR 054. 把二叉搜索树转换为累加树

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

解题思路

  • 改造中序遍历算法
  • 先遍历右子树 然后累加当前节点的值 再遍历左子树
/**
 * 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 convertBST(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);
    }
}

你可能感兴趣的:(#,Leetcode,算法,leetcode,职场和发展)