populating-next-right-pointers-in-each-node(i,ii)
来源:互联网 发布:mac apktool使用教程 编辑:程序博客网 时间:2024/06/07 03:28
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
第一问:给出的二叉树是完全二叉树
代码如下:
/** * 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; TreeLinkNode *p=root,*q; while(p->left)//注意这句话 { q=p; while(q) { q->left->next=q->right; if(q->next) { q->right->next=q->next->left; } q=q->next; } p=p->left; } }};
第二问:给出的二叉树是任意二叉树
代码如下:
/** * 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) { while(root){ TreeLinkNode lqq(-1),*pre=&lqq; while(root){ if(root->left) { pre->next=root->left; pre=pre->next; } if(root->right) { pre->next=root->right; pre=pre->next; } root=root->next; } root=lqq.next; } }};
阅读全文
0 0
- populating-next-right-pointers-in-each-node(i,ii)
- Populating Next Right Pointers in Each Node (I & II)
- 【LeetCode】Populating Next Right Pointers in Each Node I & II
- Populating Next Right Pointers in Each Node I&II
- Populating Next Right Pointers in Each Node I & II
- LeetCode:Populating Next Right Pointers in Each Node I & II
- Populating Next Right Pointers in Each Node I & II
- [LeetCode] Populating Next Right Pointers in Each Node I &II
- LeetCode:Populating Next Right Pointers in Each Node I&II
- [Leetcode]Populating Next Right Pointers in Each Node I && II
- LeetCode - Populating Next Right Pointers in Each Node I && II
- Populating Next Right Pointers in Each Node I, II
- 【leetcode】Populating Next Right Pointers in Each Node I&&II
- [LeetCode] Populating Next Right Pointers in Each Node I, II
- Populating Next Right Pointers in Each Node I, II
- 116. Populating Next Right Pointers in Each Node I&II
- [LeetCode]Populating Next Right Pointers in Each Node I & II
- Populating Next Right Pointers in Each Node I, II
- 广义表
- 小白java笔记——UML介绍
- 2014-03-28-JDK环境变量配置
- 【esp8266】MCU下arduino uno添加LED开关代码示例
- js通过正表达式获取链接参数id
- populating-next-right-pointers-in-each-node(i,ii)
- ubuntu 16.04 LTS
- init.rc启动 shell脚本
- React.js入门与案例开发
- android makefile批处理文件夹的资源
- try-catch-finally执行顺序及多return语句效果
- 2014-03-28-vs2008破解
- 关于谷歌控制台存在的一个问题
- Java Markdown