My program throws out a null pointer runtime error at running


  • 0
    X
        public class Solution {
        public void connect(TreeLinkNode root) {
            if(root.left == null || root == null || root.right == null) return;
            
            root.left.next = root.right;
            if(root.next != null)
                root.right.next = root.next.left;
                
            connect(root.left);
            connect(root.right);
        }
    }
    

    My code through out a runtime null pointer error. Anyone knows the problem?

    My thought is each node is responsible for filling the next pointer of its child nodes. So if a node doesn't have any child nodes, then the function immediately return, that's what the first statement in the function means.


  • 0
    S

    Change the order in this line

    if(root.left == null || root == null || root.right == null) return;
    

    to

    if(root== null || root.left == null || root.right == null) return;
    

    If root is null, root.left will hit the runtime error before exiting the function.


  • 0
    Z

    Hi, ShangriLa! If we don't use the recursive way here, can we change the last two recursive function into two while loop in the beginning? Thanks!!


  • 0
    S

    Here is another sharing. Is it what you are looking for?


Log in to reply
 

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