码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Populating Next Right Pointers in Each Node

时间:2015-06-17 00:30:04      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

 

Populating Next Right Pointers in Each Node

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

 

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

 

For example,
Given the following perfect binary tree,

         1
       /        2    3
     / \  /     4  5  6  7

 

After calling your function, the tree should look like:

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

 https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

 

 


 

 

树的按层遍历,其实就是bfs。

维护一个队列放每一层的节点,在每一轮中,把这一层的节点按照顺序连起来。

因为是树的结构,访问过的节点不会再访问,不需要bfs的visited对象。 

Populating Next Right Pointers in Each Node II同样的代码就能过,但是II要求不能用额外的空间。

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * function TreeLinkNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeLinkNode} root
10  * @return {void} Do not return anything, modify tree in-place instead.
11  */
12 var connect = function(root) {
13     var queue = [];
14     queue.push(root);
15     bfs();
16 
17     function bfs(){
18         if(queue.length > 0){
19             var top = null;
20             var newQueue = [];
21             var preNode = null;
22             while(top = queue.shift()){
23                 if(top.left){
24                     newQueue.push(top.left);
25                     if(preNode){
26                         preNode.next = top.left;
27                     }
28                     preNode = top.left;
29                 }
30                 if(top.right){
31                     newQueue.push(top.right);
32                     if(preNode){
33                         preNode.next = top.right;
34                     }
35                     preNode = top.right;
36                 }
37             }
38             if(preNode){
39                 preNode.next = null;
40             }
41             queue = newQueue;
42             bfs();
43         }
44     }
45 };

 

 

 

[LeetCode][JavaScript]Populating Next Right Pointers in Each Node

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4582146.html

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