A java solution, easy to understand


  • 0
    Q
    public class Solution {
    public void connect(TreeLinkNode root) {
        if(root == null) return;
        root.next = null;
        build(root.left,root.right);
    }
    private void build(TreeLinkNode parent, TreeLinkNode uncle) {
        if(parent==null && uncle==null) return;
        childBound(parent);
        childBound(uncle);
        parent.next = uncle;
        if(parent.right != null) parent.right.next = uncle.left;
        build(parent.left,parent.right);
        build(parent.right,uncle.left);
        build(uncle.left,uncle.right);
    }
    private void childBound(TreeLinkNode p) {
        if(p == null) return;
        if(p.left != null) p.left.next = p.right;
    }
    

    }


Log in to reply
 

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