您的位置:首页 > Web前端 > Node.js

Leetcode 116 Populating Next Right Pointers in Each Node 二叉树填充next指针指向右侧结点

2015-07-01 14:45 1161 查看
原题地址:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

题目描述

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.

填充二叉树,使得每个结点的next指针指向其右侧的结点。如果没有右侧结点,next指针指向NULL。

Initially, all next pointers are set to NULL.

初始情况下,所有的next指针都指向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


解题思路

如果可以用额外空间的话,用一个队列就可以轻松解决问题,然而现在不让用extra space。

我们再观察发现,其实整个过程就是把左子树的右边界点和右子树的左边界点连接起来,因为是完整二叉树,所以基本上没有什么特殊情况。唯一需要注意的是,一棵子树的右边界结点有很多个,每一层最右侧都有,相对应的一棵子树的左边界结点也有很多,我们在连接的时候要保证把每一层的边界结点都连接起来。最后再递归处理左右子树就好了。

(1)初始情况
1  <--- 当前被处理的树的根结点
/  \
2    3
/ \  / \
4  5  6  7

(2)第一步,连接第一层边界结点
1  <--- 当前被处理的树的根结点
/  \
2 -> 3  <--- 连接第一层
/ \  / \
4  5  6  7

(3)第二步,连接第二层的边界结点
1  <--- 当前被处理的树的根结点
/  \
2 -> 3
/ \  / \
4  5->6  7  <--- 连接第二层

(4)第三步,递归处理左右子树,对以下两棵树应用(1)-(4)的过程
左子树:                          右子树:
2  <--- 当前被处理的树的根结点      3  <--- 当前被处理的树的根结点
/ \                             / \
4   5                           6   7


算法描述

如果根结点为空,返回

left指向根结点的左结点,right指向根结点的右结点。

left不为空时,left->next指向right。然后left指向left->right,right指向right->left。重复3。

代码 c

void connect(struct TreeLinkNode *root) {
if (root == NULL) return;
struct TreeLinkNode *left = root->left, *right = root->right;
while (left != NULL) {
left->next = right;
left = left->right;
right = right->left;
}

connect(root->left);
connect(root->right);
}


完整代码 https://github.com/Orange1991/leetcode/blob/master/116/c/main.c

运行情况

Status:Accept

Time:4ms

代码 cpp

基本与c语言版本的相同。

class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == NULL) return;
TreeLinkNode *left = root->left, *right = root->right;
while (left != NULL) {
left->next = right;
left = left->right;
right = right->left;
}

connect(root->left);
connect(root->right);
}
};


完整代码 https://github.com/Orange1991/leetcode/blob/master/116/cpp/main.cpp

运行情况

Status:Accept

Time:28ms

// sfg1991@163.com

// 2015/7/1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: