首页 > 其他 > 详细

[Leetcode] Populating Next Right Pointers in Each Node II

时间:2014-11-15 18:18:20      阅读:117      评论:0      收藏:0      [点我收藏+]

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

 

For example,
Given the following binary tree,

         1
       /        2    3
     / \        4   5    7

 

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \        4-> 5 -> 7 -> NULL

 

Solution:

http://blog.csdn.net/wzy_1988/article/details/17412025

这道题目首要是找到右孩子的第一个有效的next链接节点,然后再处理左孩子。然后依次递归处理右孩子,左孩子

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * public class TreeLinkNode {
 4  *     int val;
 5  *     TreeLinkNode left, right, next;
 6  *     TreeLinkNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public void connect(TreeLinkNode root) {
11         if (root == null)
12             return;
13         TreeLinkNode p = root.next;
14         while (p != null) {
15             if(p.left!=null){
16                 p=p.left;
17                 break;
18             }
19             if(p.right!=null){
20                 p=p=p.right;
21                 break;
22             }
23             p=p.next;
24         }
25         if (root.right != null) {
26             root.right.next = p;
27         }
28         if (root.left != null) {
29             root.left.next = (root.right == null) ? p : root.right;
30         }
31         connect(root.right);
32         connect(root.left);
33     }
34 }

 

[Leetcode] Populating Next Right Pointers in Each Node II

原文:http://www.cnblogs.com/Phoebe815/p/4099542.html

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