码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Populating Next Right Pointers in Each Node II

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

标签:style   blog   http   io   color   ar   sp   for   div   

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

标签:style   blog   http   io   color   ar   sp   for   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!