• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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

复杂度

时间 O(N) 空间 O(N)

思路

相当于是Level Order遍历二叉树。通过一个Queue来控制每层的遍历,注意处理该层最后一个节点的特殊情况。此方法同样可解第二题。

 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         TreeLinkNode pre = null;
12         if (root == null) return;
13         Queue<TreeLinkNode> queue = new LinkedList<>();
14         queue.offer(root);
15         while (!queue.isEmpty()) {
16             int size = queue.size();
17             for (int i=0; i<size; i++) {
18                 TreeLinkNode cur = queue.poll();
19                 if (pre == null) pre = cur;
20                 else {
21                     pre.next = cur;
22                     pre = cur;
23                 }
24                 if (cur.left != null) queue.offer(cur.left);
25                 if (cur.right != null) queue.offer(cur.right);
26             }
27             pre = null;
28         }
29     }
30 }

 

 

没想到的方法:因为guarantee了是perfect binary tree

层次递进法

复杂度

时间 O(N) 空间 O(1)

 1 public class Solution {
 2     public void connect(TreeLinkNode root) {
 3         if(root==null) return;
 4         TreeLinkNode cur = root;
 5         TreeLinkNode nextLeftmost = null;
 6 
 7         while(cur.left!=null){
 8             nextLeftmost = cur.left; // save the start of next level
 9             while(cur!=null){
10                 cur.left.next=cur.right;
11                 cur.right.next = cur.next==null? null : cur.next.left;
12                 cur=cur.next;
13             }
14             cur=nextLeftmost;  // point to next level 
15         }
16     }
17 }

 

posted @ 2014-09-18 06:38  neverlandly  阅读(365)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3