Populating Next Right Pointers in Each Node
2016-05-04 00:02
489 查看
116. 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
#include <iostream> #include <vector> #include <string> #include <sstream> #include <stack> #include <iostream> #include <algorithm> #include <math.h> #include <limits.h> using namespace std; struct TreeLinkNode { int val; TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; TreeLinkNode(int val){ this->val=val; this->left = this->right=this->next = NULL; } }; void process(TreeLinkNode *cur,TreeLinkNode *nextNode){ if(cur==NULL) { return; } if(nextNode==NULL) { cur->next=NULL; return; } cur->next=nextNode; process(cur->left,cur->right); process(cur->right,cur->next->left); } void preProcess(TreeLinkNode *root){//预处理,先将右边节点 指向自己。 if(root == NULL) return; root->next=root; preProcess(root->right); } void afterProcess(TreeLinkNode *root){//后处理,先将右边节点 指向NULL。 if(root == NULL) return; root->next=NULL; afterProcess(root->right); } void connect(TreeLinkNode *root) { if(root == NULL) return; preProcess(root); process(root->left,root->right); process(root->right,root->next->left); afterProcess(root); } int main(){ TreeLinkNode* root=new TreeLinkNode(0);//test1 root->left=new TreeLinkNode(1); root->right=new TreeLinkNode(2); root->left->left=new TreeLinkNode(3); root->left->right=new TreeLinkNode(4); root->right->left=new TreeLinkNode(5); root->right->right=new TreeLinkNode(6); connect(root); cout<< "maxPathSum(root)="<<endl; system("pause"); }
相关文章推荐
- 搭建nodejs的express框架
- 在nodejs下express 从安装到运行的全过程
- Node.js学习-1
- Node.js异步读取txt文档
- Nodejs学习item 2 -- events事件处理EventEmitter
- Node.JS创建服务
- 237. Delete Node in a Linked List
- Nodejs学习item 1 -- 入门手上
- 通过ffi在nodejs中调用动态链接库(.so文件)
- 美团酒店Node全栈开发实践
- Node.js知识分类
- Leetcode题解14 237. Delete Node in a Linked List
- nodejs php go语言了解
- Zookeeper的节点znode
- 如何升级nodejs版本
- Node和Element的区别
- GetJsonNodeValue , GetJsonNodeValueFromFirstArrayItem 取JSON节点的值
- [笔记] Node-Link可视化图中移动Node后自动布局调整算法
- Debian上安装Node.js和npm
- LeetCode 24. Swap Nodes in Pairs