LeetCode Populating Next Right Pointers in Each Node
来源:互联网 发布:洛奇英雄传多核优化 编辑:程序博客网 时间:2024/04/28 18:34
这题很有新意,刚开始想到后序遍历,可是对于给的例子5和6之间怎么连接呢?无论怎么遍历5和6之间都隔好几个数,递归引用传参数的方法肯定不行,题中又说常量的空间,对于完全二叉树最多也不过64层吧,所以每一层设定一个指针用于建立连接。传递指针数组不太容易,用了全局变量解决。如下:
// LeetCode_PopulatingNextRightPointers.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;struct TreeLinkNode { int val; TreeLinkNode *left, *right, *next; TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} };TreeLinkNode* layers[64];void preOrderLayer(TreeLinkNode *root,int layer)//,TreeLinkNode *&layers{if (layers[layer]==NULL){layers[layer] = root;}else{layers[layer]->next = root;layers[layer] = root;}if(root->left)preOrderLayer(root->left,layer+1);if(root->right)preOrderLayer(root->right,layer+1);}void connect(TreeLinkNode *root) {if(root==NULL)return ;for (int i=0;i<64;i++)layers[i] = NULL;int layer = 0;preOrderLayer(root,layer);for (int i=0;i<64&&layers[i]!=NULL;i++){layers[i]->next = NULL;}}int _tmain(int argc, _TCHAR* argv[]){TreeLinkNode *pa = new TreeLinkNode(1); TreeLinkNode *pb = new TreeLinkNode(2); TreeLinkNode *pc = new TreeLinkNode(3); TreeLinkNode *pd = new TreeLinkNode(4);//TreeLinkNode *pd = NULL;// TreeLinkNode *pe = new TreeLinkNode(5); TreeLinkNode *pf = new TreeLinkNode(6); TreeLinkNode *pg = new TreeLinkNode(7); pa->left = pb; pa->right = pc; pb->left = pd; pb->right = pe; pc->left = pf; pc->right = pg; connect(pa);system("pause");return 0;}
0 0
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node &&Populating Next Right Pointers in Each Node||
- LeetCode Populating Next Right Pointers in Each Node & Populating Next Right Pointers in Each Node I
- 【Leetcode】Populating Next Right Pointers in Each Node in JAVA
- LeetCode Populating Next Right Pointers in Each Node
- LeetCode Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node
- LeetCode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node II
- 【leetcode】 Populating Next Right Pointers in Each Node
- leetcode 78: Populating Next Right Pointers in Each Node
- leetcode 79: Populating Next Right Pointers in Each Node II
- Leetcode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node ii
- leetcode Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node
- Fedora9 NFS配置
- linux free
- 2013.03.13 bootstrap 模态框使用
- ZOJ 3736 模拟魔方
- linux feof
- LeetCode Populating Next Right Pointers in Each Node
- 特征变换以及维度下降——前言
- (22)Formatter格式化类
- 2012蓝桥杯C++本科 大数乘法
- 进程入门之CreateProcess
- linux calloc
- 嘿嘿 CSDN在线培训:用SQL-on-Hadoop构建互联网数据仓库与商务智能系统
- 树的最大独立集 (算法经典入门)
- 变量简介