Populating Next Right Pointers in Each Node

本文介绍了一种在完美二叉树中填充每个节点的next指针的方法,使得每个节点指向其右侧相邻节点。提供了一种递归解决方案,并确保只使用常数额外空间。

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 toNULL.

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

solution:
这其实就是个BFS,使用一个队列既可,为了方便,在每一层扩展完之后向队列中加入一个null。在对next point 赋值时,如果发现下一项是null,则直接给next = null.

由于只能使用constant 空间,所以不能这么做,由于是一棵树,所以考虑递归。
 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         // Start typing your Java solution below
12         // DO NOT write main() function
13         if(root == null) return;
14         if(root.left != null){
15             root.left.next = root.right;
16         }
17         if(root.right != null){
18             root.right.next = ((root.next != null)? root.next.left : null);
19         }
20         connect(root.left);
21         connect(root.right);
22     }
23 }

 

转载于:https://www.cnblogs.com/reynold-lei/p/3313824.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值