首页 > 其他 > 详细

Populating Next Right Pointers in Each Node II

时间:2014-02-17 16:45:21      阅读:349      评论: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?

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
bubuko.com,布布扣
 1 public class Solution {
 2     public void connect(TreeLinkNode root) {
 3         TreeLinkNode left = root;
 4         while(left!=null){
 5             TreeLinkNode across = left;
 6             TreeLinkNode leftMost = null;
 7             while(across!=null){
 8                 if(across.left!=null){
 9                     if(leftMost==null)
10                         leftMost = across.left;
11                     across.left.next = findNextRight(across,true);
12                 }
13                 if(across.right!=null){
14                     if(leftMost==null)
15                         leftMost = across.right;
16                     across.right.next = findNextRight(across,false);
17                 }
18                 across = across.next;
19             }
20             left = leftMost;
21         }
22     }
23     public TreeLinkNode findNextRight(TreeLinkNode root,boolean isLeft){
24         if(isLeft){
25             if(root.right!=null) return root.right;
26         }
27         root = root.next;
28         while(root!=null){
29             if(root.left!=null)
30                 return root.left;
31             if(root.right!=null)
32                 return root.right;
33             root = root.next;
34         }
35         return null;
36     
37     }
38 }
View Code

 

 

Populating Next Right Pointers in Each Node II

原文:http://www.cnblogs.com/krunning/p/3552033.html

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