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

LeetCode OJ 116. Populating Next Right Pointers in Each Node

时间:2016-05-04 19:06:22      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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

 

对于这个题目我们可以很方便的采用层序遍历来解决,每次遍历一层把下一层的节点依次连接起来。由于每一层相当于形成了一个链表,树的最左边的节点就是每一层的起始节点。我们遍历这个链表,把链表中每一个节点的左右节点相连,然后把链表中相邻节点的左孩子和右孩子相连即可。

代码如下:

 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) return;
12         TreeLinkNode temp = root;
13         if(temp.left!=null){
14             while(temp!=null){    //遍历一层
15                 temp.left.next = temp.right;
16                 if(temp.next!=null){
17                     temp.right.next = temp.next.left;
18                 }
19                 else{
20                     temp.right.next = null;
21                 }
22                 temp = temp.next;
23             }
24             connect(root.left);    //遍历下一层
25         }
26         return;
27     }
28 }

 

LeetCode OJ 116. Populating Next Right Pointers in Each Node

标签:

原文地址:http://www.cnblogs.com/liujinhong/p/5459290.html

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