LeetCode (Populating Next Right Pointers in Each Node)
来源:互联网 发布:淘宝无线端装修 编辑:程序博客网 时间:2024/06/09 14:38
Problem:
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
Solution:/** * 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) { vector<TreeLinkNode*> pre(1, root); while(pre.front()){ vector<TreeLinkNode*> next; for(int i = 0; i < pre.size(); i++){ next.push_back(pre[i]->left); next.push_back(pre[i]->right); pre[i]->next = (i == pre.size() - 1) ? NULL : pre[i + 1]; } pre = next; } }};
阅读全文
0 0
- 【LeetCode】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||
- LeetCode Populating Next Right Pointers in Each Node & Populating Next Right Pointers in Each Node I
- 【Leetcode】Populating Next Right Pointers in Each Node in JAVA
- LeetCode Populating Next Right Pointers in Each Node
- LeetCode Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node
- LeetCode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node II
- 【leetcode】 Populating Next Right Pointers in Each Node
- leetcode 78: Populating Next Right Pointers in Each Node
- leetcode 79: Populating Next Right Pointers in Each Node II
- Leetcode: Populating Next Right Pointers in Each Node
- [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
- 如何配置Java环境安装eclipse
- CentOS6.5 RPM方式安装MySQL5.6
- block和delegate修饰符:
- POJ 1503 Integer Inquiry 笔记
- 树的子结构
- LeetCode (Populating Next Right Pointers in Each Node)
- 树状数组
- 遍历二叉树
- C++设计模式一--StrategyPattern(策略模式)
- mysqldumpslow使用总结
- 全面解读Java NIO工作原理
- 79_游戏项目_动画的实现
- DIV 居中
- codeforces817c Really Big Numbers