Populating Next Right Pointers in Each Node II
来源:互联网 发布:求数组最大值和最小值 编辑:程序博客网 时间:2024/05/01 06:24
题目大意:二叉树里面每个节点都有一个next指针,要求使得每个节点的next指针指向这一层的最先遇到的节点。
解题思路:宽度遍历。
#include <iostream>#include <cstdio>#include <queue>using namespace std;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 *> node_queue; node_queue.push(root); while(!node_queue.empty()) { TreeLinkNode *node = node_queue.front(); node_queue.pop(); if(node->left != NULL) { connectAssist(node->left, node); node_queue.push(node->left); } if(node->right != NULL) { connectAssist(node->right, node); node_queue.push(node->right); } } }private: void connectAssist(TreeLinkNode *cur_node, TreeLinkNode *parent) { if(cur_node != NULL) { if(parent == NULL) { cur_node->next = NULL; } else { if(cur_node == parent->left) { if(parent->right != NULL) { cur_node->next = parent->right; } else { cur_node->next = getParentNextChild(parent->next); } } else { cur_node->next = getParentNextChild(parent->next); } } connectAssist(cur_node->left, cur_node); connectAssist(cur_node->right, cur_node); } } TreeLinkNode *getParentNextChild(TreeLinkNode *parent_node) { if(parent_node == NULL) return NULL; TreeLinkNode *node = NULL; while(parent_node) { if(parent_node->left != NULL) { node = parent_node->left; break; } if(parent_node->right != NULL) { node = parent_node->right; break; } parent_node = parent_node->next; } return node; }};
0 0
- 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 II
- 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 II
- leetcode 79: 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 II
- 【leetcode】Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- [Leetcode]Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node (I & II)
- Populating Next Right Pointers in Each Node II
- 【java编程】Collections工具类之复写reserve方法
- 【转载】Linux系统启动过程分析
- 新建的cocos2d-x中各文件的作用
- JAVA中通过接口实现方法重写
- ExtJS Direct 的Java实现——DJN
- Populating Next Right Pointers in Each Node II
- uva 11177 圆与凸多边形交
- POJ 2116解题报告
- 值传递与引用值传递 的区别
- ListView多种布局的优化
- 深拷贝和浅拷贝(copy)的区别
- 花开时间恰逢君
- singleton
- Android 打造编译时注解解析框架 这只是一个开始