本质上是二叉树的层次遍历,遍历层次的过程当中把next指针加上去。

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

和问题"Populating Next Right Pointers in Each Node"类似。

如果给定的树是任意的二叉树,你先前的方法还能工作吗?

笔记:

  • 你只能用常量的辅助空间。

例如给定的是羡慕的二叉树,

         1
/ \
2 3
/ \ \
4 5 7
当调用完你的函数后,这个树应该看起来想这样子:
         1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
/ \
2 3
/ \ \
4 5 7

After calling your function, the tree should look like:

         1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
 
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include "BinaryTreeWithNext.h"

using namespace std;

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
void connect(TreeLinkNode *root)
{
    if(root == NULL)
    {
        return ;
    }
    vector<TreeLinkNode *> vec;
    vec.push_back(root);
    int count = 1;
    while(!vec.empty())
    {
        if(count > 1)
        {
            vec[0]->next = vec[1];
        }
        else
        {
            vec[0]->next = NULL;
        }

        if(vec[0]->left != NULL)
        {
            vec.push_back(vec[0]->left);
        }
        if(vec[0]->right != NULL)
        {
            vec.push_back(vec[0]->right);
        }
        vec.erase(vec.begin());
        count--;

if(count == 0)
        {
            count = vec.size();
        }
    }
}

// 树中结点含有分叉,
//                  1
//              /       \
//             2         3
//           /   \         \
//          4     5         7
int main()
{
    TreeLinkNode *pNodeA1 = CreateBinaryTreeNode(1);
    TreeLinkNode *pNodeA2 = CreateBinaryTreeNode(2);
    TreeLinkNode *pNodeA3 = CreateBinaryTreeNode(3);
    TreeLinkNode *pNodeA4 = CreateBinaryTreeNode(4);
    TreeLinkNode *pNodeA5 = CreateBinaryTreeNode(5);
    TreeLinkNode *pNodeA6 = CreateBinaryTreeNode(7);

ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
    ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
    ConnectTreeNodes(pNodeA3, NULL, pNodeA6);

connect(pNodeA1);

TreeLinkNode *trav = pNodeA1;
    TreeLinkNode *tmp;
    while (trav != NULL)
    {
        tmp = trav;
        while(tmp)
        {
            cout << tmp->val << " ";
            tmp = tmp->next;
        }
        cout << endl;
        trav = trav->left;
    }
    cout << endl;

DestroyTree(pNodeA1);
    return 0;
}

结果输出:
1
2 3
4 5 7
 
 
BinaryTreeWithNext.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
#ifndef _BINARY_TREE_WITH_NEXT_H_
#define _BINARY_TREE_WITH_NEXT_H_

struct TreeLinkNode
{
    int val;
    TreeLinkNode *left;
    TreeLinkNode *right;
    TreeLinkNode *next;
    TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};

TreeLinkNode *CreateBinaryTreeNode(int value);
void ConnectTreeNodes(TreeLinkNode *pParent,
                      TreeLinkNode *pLeft, TreeLinkNode *pRight);
void PrintTreeNode(TreeLinkNode *pNode);
void PrintTree(TreeLinkNode *pRoot);
void DestroyTree(TreeLinkNode *pRoot);

#endif /*_BINARY_TREE_WITH_NEXT_H_*/

BinaryTreeWithNext.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
 
#include <iostream>
#include <cstdio>
#include "BinaryTreeWithNext.h"

using namespace std;

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
//创建结点
TreeLinkNode *CreateBinaryTreeNode(int value)
{
    TreeLinkNode *pNode = new TreeLinkNode(value);

return pNode;
}

//连接结点
void ConnectTreeNodes(TreeLinkNode *pParent, TreeLinkNode *pLeft, TreeLinkNode *pRight)
{
    if(pParent != NULL)
    {
        pParent->left = pLeft;
        pParent->right = pRight;
    }
}

//打印节点内容以及左右子结点内容
void PrintTreeNode(TreeLinkNode *pNode)
{
    if(pNode != NULL)
    {
        printf("value of this node is: %d\n", pNode->val);

if(pNode->left != NULL)
            printf("value of its left child is: %d.\n", pNode->left->val);
        else
            printf("left child is null.\n");

if(pNode->right != NULL)
            printf("value of its right child is: %d.\n", pNode->right->val);
        else
            printf("right child is null.\n");
    }
    else
    {
        printf("this node is null.\n");
    }

printf("\n");
}

//前序遍历递归方法打印结点内容
void PrintTree(TreeLinkNode *pRoot)
{
    PrintTreeNode(pRoot);

if(pRoot != NULL)
    {
        if(pRoot->left != NULL)
            PrintTree(pRoot->left);

if(pRoot->right != NULL)
            PrintTree(pRoot->right);
    }
}

void DestroyTree(TreeLinkNode *pRoot)
{
    if(pRoot != NULL)
    {
        TreeLinkNode *pLeft = pRoot->left;
        TreeLinkNode *pRight = pRoot->right;

delete pRoot;
        pRoot = NULL;

DestroyTree(pLeft);
        DestroyTree(pRight);
    }
}

 
 

【遍历二叉树】12往二叉树中添加层次链表的信息【Populating Next Right Pointers in Each Node II】的更多相关文章

  1. Web前端开发最佳实践(4):在页面中添加必要的meta信息

    meta标签放置在HTML页面的head中,主要用于标识网站.其中基本上包含了网站的一些描述信息,例如,简介.作者等.这些信息有助于搜索引擎更准确地识别网页的内容,也有助于第三方工具抓取网站基本信息. ...

  2. 【LeetCode】 Populating Next Right Pointers in Each Node 全然二叉树

    题目:Populating Next Right Pointers in Each Node <span style="font-size:18px;">/* * Le ...

  3. 如何使用django操作数据库,向原有表中添加新的字段信息并建立一个多对多的关系?

    (注:本人用的pycharm开发工具) 1.在你要添加新字段的app的 models.py 文件中添加需要新增的字段(book表新增authors字段并和author建立多对多关系,author表新增 ...

  4. 【二叉树的递归】06填充每个节点中的下一个正确的指针【Populating Next Right Pointers in Each Node】

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定一个二叉树 struct Tr ...

  5. Populating Next Right Pointers in Each Node 设置二叉树的next节点

    Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *nex ...

  6. IDEA中添加类的创建者信息

    创建方法: 1. 使用快捷键(ctrl + alt + s),在弹出框中左边侧选择 Editor -> File and Code Templates,左边侧相应会更新 右边侧选择 Class, ...

  7. Qt实现 动态化遍历二叉树(前中后层次遍历)

    binarytree.h 头文件 #ifndef LINKEDBINARYTREE_H #define LINKEDBINARYTREE_H #include<c++/algorithm> ...

  8. JS向固定数组中添加不重复元素并冒泡排序

    向数组{7,20,12,6,25}中添加一个不重复的数字,然后按照从小到大的顺序排列 源代码: <!DOCTYPE html> <html> <head> < ...

  9. Python之向日志输出中添加上下文信息

    除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如:远程客户端的IP地址和用户名.这里我们 ...

随机推荐

  1. CAShapeLayer实现圆形进度条效果

    一.CAShapeLayer简单介绍: .CAShapeLayer继承至CALayer,能够使用CALayer的全部属性值 2.CAShapeLayer须要与贝塞尔曲线配合使用才有意义 3.使用CAS ...

  2. python多任务处理

    多任务解析 什么叫“多任务”呢?简单地说,就是操作系统可以同时运行多个任务. 现在,多核CPU已经非常普及了,但是,即使过去的单核CPU,也可以执行 多任务.由于CPU执行代码都是顺序执行的,那么,单 ...

  3. 【python】-- 函数、无参/有参参数、全局变量/局部变量

    函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.你已经知道Python提供了许多内建函数,比如print().但你也可以自己创建函 ...

  4. 【译】常见 Java 异常解释(恶搞版)

    常见 Java 异常解释:(译者注:非技术角度分析.阅读有风险,理解需谨慎o(╯□╰)o) java.lang ArithmeticException 你正在试图使用电脑解决一个自己解决不了的数学问题 ...

  5. [note]树链剖分

    树链剖分https://www.luogu.org/problemnew/show/P3384 概念 树链剖分,是一种将树剖分成多条不相交的链的算法,并通过其他的数据结构来维护这些链上的信息. 最简单 ...

  6. mysql mariadb 乱码

    mysql 创建临时表 CREATE TEMPORARY TABLE tmp_table SELECT COUNT(*) AS num FROM student_info GROUP BY LEFT( ...

  7. Tensorflow 初级教程(二)

    一.Tensorflow 扩展功能 1.自动求导 2.子图的执行 3.计算图控制流 4.队列/容器 Tensorflow 自动求导 当计算tensor C关于tensor W的梯度时,会先寻找从W到C ...

  8. HackerRank - angry-children 【排序】

    题意 求一个序列当中 其 长度为 K 的子序列 中的 最大值 - 最小值 求 这个值 最小是多少 思路 先将序列排序 然后 I = 0, J = K - 1 然后 往下遍历 如果 arr[j] - a ...

  9. HIVE 总结

    http://blog.csdn.net/wisgood/article/details/17186181 常见错误 http://blog.csdn.net/sunnyyoona/article/d ...

  10. vo优化总结

    问题1:位姿估计用的ransac,只用了几个点,如果3d_2d点存在噪声,不行.优化:把这值当做初值,用非线性优化问题2:深度图有误差,深度过近或过远不行,有误差.而特征点往往在物体边缘处,深度测量值 ...