【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II
2016-07-04 20:19
381 查看
一天一道LeetCode
(一)题目
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
(二)解题
参考:【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node没想到昨天做的解法直接把今天的题给解了。一模一样的代码,请跳转到上题的解题思路:
/** * 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) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { if(root==NULL) return; queue<TreeLinkNode *> myque; myque.push(root); while(!myque.empty()) { queue<TreeLinkNode *> temp_que; TreeLinkNode *pre = NULL; while(!myque.empty()) { TreeLinkNode *temp = myque.front(); myque.pop(); if(pre==NULL) pre = temp;//相当于每一层的头节点 else { pre->next = temp;//用next指针连接每一层的节点 pre = temp; } if(temp->left!=NULL) temp_que.push(temp->left);//下一层 if(temp->right!=NULL) temp_que.push(temp->right);//下一层 } pre->next=NULL;//最后一个节点的next需要指向NULL myque=temp_que;//进入下一层操作 } } };
相关文章推荐
- 【leetcode】19. Remove Nth Node From End of List
- 为什么 nodejs 外部的 reactnative 无法启动,因为没有配置环境变量.
- 搭建一个简单的node.js服务器
- Node.js: managing child processes
- 117. Populating Next Right Pointers in Each Node II
- nodejs基础概念解析
- window下通过nvmw来安装多版本node
- 116. Populating Next Right Pointers in Each Node
- 分布式存储ceph系统性能不稳定因素
- DrawNode
- Nodejs中 npm常用命令详解
- Nodejs全局安装和本地安装的不同之处
- [算法]Java 实现 简单MyNode类型 无序链表 递归 添加 删除 遍历
- 【原】nodejs全局安装和本地安装的区别
- 24. Swap Nodes in Pairs
- bower安装库出现的问题解决办法
- Node.js Streams文件读写操作详解
- 【web】Ubuntu上安装nodejs 4.x 5.x版本方法
- node 关键点总结
- node.js池操作