0

Got two methods:

public void getBalance(){
    balance(root);
}

private void balance(TreeNode node) {


    if (node != null && node.left != null) {
        balance(node.left);
        balance(node.right);
        System.out.println(node.left);
        //sout work fine
    }
}

need to return value from balance();

if I change return value from void to TreeNode, and change code

    private TreeNode balance(TreeNode node) {


    if (node != null && node.left != null) {
        balance(node.left);
        balance(node.right);
        return node.left;

    }
    return balance(node);
}

return sStackOverflowError Exception.

I need to return node left from this method.

Please help.

IMBABOT
  • 121
  • 2
  • 12
  • 1
    what do you expect if `node` is null or `node.left` is null? – jhamon Aug 13 '18 at 12:06
  • also: how do you expect a method with return type void to return anything? – Stultuske Aug 13 '18 at 12:07
  • 1
    If `node` is `null`, you keep on invoking `balance` recursively - that's *likely* the reason for your `StackOverflowError`. – Mena Aug 13 '18 at 12:08
  • node.left is not null, and IF change return value from void to TreeNode, method return StackOverflowError Exception. – IMBABOT Aug 13 '18 at 12:10
  • `node.left`may not be null, but one of its linked node or subnode is null. So, what do you expect to get if `node` is null or `node.left` is null? – jhamon Aug 13 '18 at 12:19
  • you may have many node left, so which node left do you want? the low level or high level? – clevertension Aug 13 '18 at 12:19
  • root node do not have link to high level nodes, and I pass root element which does not have high nodes. – IMBABOT Aug 13 '18 at 12:27
  • `root` node has a `left` node and a `right` node. Calling balance of root node, call balance on those too – jhamon Aug 13 '18 at 12:31
  • you can avoid stack overflow changing your design and use while instead of recursive method. you can find a general design pattern to do it in this: http://www.jndanial.com/73 – Danial Jalalnouri Sep 18 '18 at 22:21

0 Answers0