Jan 30 - Populating Next Right Pointers To Each Node; Iteration & Recursion; Tree; Pointer;

3120 단어
In this problem, we cannot find an efficient recursion way to set up the next pointer.
For example, we can do like this, in this way we may set up too many next pointer repeatedly.
Code:
/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        connect(root.left, root.right);
        
    }
    
    public void connect(TreeLinkNode left, TreeLinkNode right){
        if(left == null) return;
        
        left.next = right;
        connect(left.left, left.right);
        connect(left.right, right.left);
        connect(right.left, right.right);
    }
}
    

However, we can do the set up next pointer efficiently using iterative way.
We use two pointer to do the set up operation. The head pointer points to the current node in a certain level. Pointer parent points to the parent of current ndoe. If head == null, we've reached to the bottom of the tree. Traversal completes. For a existed node, head.next = parent.right. And if parent.next exists, we should let parent.right.next = parent.next.left. Then go to parent.next.
Code:
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root == null) return;
        for(TreeLinkNode head = root; head != null; head = head.left){
            for(TreeLinkNode parent = head; parent != null; parent = parent.next){
                TreeLinkNode child = parent.left;
                if(child == null) return;
                child.next = parent.right;
                if(parent.next != null) parent.right.next = parent.next.left;
                }
        }
    }
    /*
    public void connect(TreeLinkNode root) {
        if(root == null || root.left == null) return;
        connect(root.left, root.right);
    }
    
    public void connect(TreeLinkNode left, TreeLinkNode right){
        if(left == null) return;
        
        left.next = right;
        connect(left.left, left.right);
        connect(left.right, right.left);
        connect(right.left, right.right);
    }
    */
}
    

좋은 웹페이지 즐겨찾기