Simple to understand solution using inorder traversal technique


  • 0
    M
    class Solution {
        private List<Integer> list = new ArrayList<>();
        public TreeNode convertBST(TreeNode root) {
            if(root == null){
                return root;
            }
            traverse(root);
            return generateTree(root);
        }
        
        private void traverse(TreeNode root){
            if(root == null){
                return;
            }
            
            traverse(root.left);
            list.add(root.val);
            traverse(root.right);
        }
        
        private TreeNode generateTree(TreeNode root){
            if(root == null){
                return root;
            }
            int sum = root.val;
            int index = list.indexOf(root.val);
            for(int i=index+1;i<list.size();i++){
                sum += list.get(i);
            }
            TreeNode node = new TreeNode(sum);
            node.left = generateTree(root.left);
            node.right = generateTree(root.right);
            return node;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.