首页 > 其他 > 详细

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

时间:2016-01-31 13:19:43      阅读:165      评论:0      收藏:0      [点我收藏+]

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);
    }
    */
}
    

 

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

原文:http://www.cnblogs.com/5683yue/p/5172931.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!