Java recursion solution...minor change leading to wrong solution


  • 0
    A

    the following solution works well , however doing some with minor changes in increement leads to wrong solution...I have marked the code which if changed pops out a wrong solution... Can anyone explain the reason?? Pls

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int value=0;
        public TreeNode addOneRow(TreeNode root, int v, int d) 
        {
            value=v;
            if(d==1)
            {
             TreeNode roott=new TreeNode(v);
             roott.left=root;
                return roott;
            }
            return solve(root,1,d);
            
        }
        
        TreeNode solve(TreeNode root,int depth,int at_depth)
        {
            
            if(root!=null)
            {
                solve(root.left,++depth,at_depth);
                
                if(depth==at_depth)
                {
                    
                    TreeNode left_child=root.left;
                    TreeNode right_child=root.right;
                    root.left=new TreeNode(value);
                    root.right=new TreeNode(value);
                    root.left.left=left_child;
                    root.right.right=right_child;
                    
                    
                }
    //////////////////HERE ////////////////////////////////
                solve(root.right,depth++,at_depth);
    ///here  "solve(root.right,++depth,at_depth) " is giving wrong solution
    //Can someone explain why??
            }
            return root; 
        }
    }
    

Log in to reply
 

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