将一行添加到二叉树

时间:2017-08-07 10:20:34

标签: java binary-tree

这是递归代码,用于在特定深度“d”的二叉树中添加一行,将行节点的值添加为“v”,但是如果我更改“深度”的后增量(我已经标记了代码)预先递增,代码不适用于所有testCases ...有人可以解释一下吗?谢谢

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); //correct code

///////here  "solve(root.right,++depth,at_depth) " is giving wrong solution////
        }
    return root; 
}
}

2 个答案:

答案 0 :(得分:0)

这棵树中的

Let we are going to insert value 2 at depth 2。 所以求解函数调用顺序将如下所示

解决(节点(8),1,2)

solve(node(5),2,2)
    solve(node(9),3,2)//at this level depth is 3
            ---here null check and recursive call ends
    solve(node(7),3,2) // depth will be passed as 3 when you put post-increment that is correct, 
    //But if you put pre-increment the depth will be 4 that is incorrect[solve(node(7),4,2) <-- wrong call].

答案 1 :(得分:0)

问题似乎在于增加变量depth

当您使用预增量运算符时,它会更改该变量的值,因为第二次调用solve()时,您已经增加了depth的值。因此,如果您尝试使用++depth再次递增,则会产生意外结果。

您不应在递归调用中使用post / pre increment运算符,而应在两个调用中使用depth+1,这样可以解决您的问题。

希望有所帮助!