【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node
2016-07-03 21:33
423 查看
一天一道LeetCode
(一)题目
来源:https://leetcode.com/problems/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
(二)解题
题目大意:定义一个新的二叉树结构,增加一个新指针next指向该节点右侧相邻的节点。解题思路:考虑到要指向右侧相邻的节点,可以采用层序遍历的方式来求解
将每一层的节点用next连接起来即可!
层序遍历可以参考:【一天一道LeetCode】#102. Binary Tree Level Order Traversal
废话不说,看AC代码:
/** * 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;//进入下一层操作 } } };
相关文章推荐
- nodejs 执行 最近 发现 nodejs 执行的 是非等待的。
- 如何给nodejs开发的web 绑定域名
- NodeJS基础1——基础介绍
- LeetCode - 92. Reverse Linked List II
- nodejs模块机制
- BUG-getContainingNode(): node module not found
- js获取子节点childNodes和children的区别
- Node.js-安装配置【1】-在Windows XP系统配置环境变量
- 使用node.js的Crypto模块Hmac算法对信息进行认证
- WebStorm NodeJS
- node版本管理 n和nvm说明
- Node.js学习心得
- NodeJS学习历程(3)
- [leetcode]19. Remove Nth Node From End of List
- Nth to Last Node in List
- Remove Nth Node From End of List
- NodeJS学习历程(2)
- 阿里云服务器搭建ghost博客之Node环境安装(一)
- 提高node性能的奇怪办法
- node.js后台jquery前台-- 实现用户登录注册AJAX交互