117. Populating Next Right Pointers in Each Node II
来源:互联网 发布:新浪微博下载mac版 编辑:程序博客网 时间:2024/06/05 00:37
题目:Populating Next Right Pointers in Each Node II
原题链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
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,
After calling your function, the tree should look like:
给出一个二叉树,让每层节点的next()指向其右边一个节点,每层最右节点指向NULL,初始next()都指向NULL。
注意:只能使用常数级额外空间。
和116题不同,这次不保证是一个完全二叉树了,只能用一般性的方法,层序遍历二叉树,每层的最右节点外,其余节点都指向层序遍历的下一个节点。
代码如下:
/** * 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) return; queue<TreeLinkNode*> q; q.push(root); // left表示每层的最左节点,pre表示取出的节点的前一个节点 TreeLinkNode *left = root, *pre; bool le = false; // 用来指示下一层的最左节点是否已经找到 while(!q.empty()) { TreeLinkNode* t = q.front(); q.pop(); if(t == left) { le = false; } else { pre->next = t; } if(t->left) { if(!le) { left = t->left; le = true; } q.push(t->left); } if(t->right) { if(!le) { left = t->right; le = true; } q.push(t->right); } pre = t; } return; }};
0 0
- LeetCode 117. Populating Next Right Pointers in Each Node II
- [LeetCode]117.Populating Next Right Pointers in Each Node II
- [Leetcode] 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- [leetcode] 117.Populating Next Right Pointers in Each Node II
- 116. Populating Next Right Pointers in Each Node && 117. II
- [LeetCode]117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- [leetcode]117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- LeetCode 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- [LeetCode] 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 求最长回文子串的四种算法
- 双系统Ubuntu 引导修复(Boot Repair)
- Photoshop纹理制作——水纹理
- 规则引擎之 行业工程应用
- 循环指令loop
- 117. Populating Next Right Pointers in Each Node II
- 欢迎使用CSDN-markdown编辑器
- C#的26课的主要内容
- 日期Date 、Calendar、SimpleDateFormat学习总结(一)
- LINUX操作系统嵌入Xenomai实时核
- 算法与数据结构实验题 4.3 不知道取什么好
- 排序和二分查找
- Spring注解实现Bean定义
- (笔记)studio里的library项目无法生成R文件