Populating Next Right Pointers in Each Node II
来源:互联网 发布:淘宝达人怎么直播 编辑:程序博客网 时间:2024/05/22 23:21
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
Discuss
/** * 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*> qu; TreeLinkNode *te; int cntb = 0; int cnta = 0; qu.push(root); cntb = 1; while(!qu.empty()) { te = qu.front(); qu.pop(); cntb--; if(cntb == 0) { te->next = NULL; if(te->left) { qu.push(te->left); cnta++; } if(te->right) { qu.push(te->right); cnta++; } cntb = cnta; cnta = 0; continue; } else te->next = qu.front(); if(te->left) { qu.push(te->left); cnta++; } if(te->right) { qu.push(te->right); cnta++; } } }};
有了上一次的基础, 一次AC应该没问题
注意的是:
queue
pop()出队
push(obj);入队
empty();
front(); 是队首, 是最先入队的那个.
也就是说, queue是尾进头出
back();同理
还有一个size();
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
- shell统计每列的重复个数
- 一天一linux命令(22) wall,write用户间发送信息
- 项目进阶 之 持续构建环境搭建(二)Nexus私服器
- Spark各部分功能
- java——reference类型和Primitive类型
- Populating Next Right Pointers in Each Node II
- Element属性方法的浏览器兼容性概览
- uva 1422 - Processor(二分+优先队列)
- MYGUI3.2改造——与HGE结合,实现资源打包
- Android之TextView使用
- Lync 2010 部署过程中碰到的问题
- Java开发中常见的危险信号(中)
- 设计模式(1) - Factory工厂模式
- 请支持我的朋友们为我投上一票