My JAVA solution, easy to understand


  • 0
    K

    public class Solution {

    // link node's left leaf to right leaf if applicable
    private void helper(TreeLinkNode tn){
        if(tn!=null){
            if(tn.left!=null) tn.left.next=tn.right;
            helper(tn.left);
            helper(tn.right);
        }
    }
    // link left-node's right leaf to right-node's left leaf if applicable
    private void helper(TreeLinkNode left,TreeLinkNode right){
        if(left!=null&&right==null) helper(left.left,left.right);
        if(left==null&&right!=null) helper(right.left,right.right);
        if(left!=null&&right!=null){
            if(left.right!=null) left.right.next=right.left;
            helper(left.left,left.right);
            helper(left.right,right.left);
            helper(right.left,right.right);
        }
    }
    public void connect(TreeLinkNode root) {
        if(root!=null){
            helper(root);
            helper(root.left,root.right);
        }
    }
    

    }


Log in to reply
 

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