leetcode:Populating Next Right Pointers in Each Node II (顺序连接二叉树每一层节点)【面试算法题】
2013-10-18 10:40
731 查看
题目:
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:
题意把二叉树每一层所有的节点顺序链接,只能开辟常数空间。
这题与上道题不同点在于二叉树不是完全二叉树,因此结构差别较大,不能用上道题的方法。
如果当前节点有左右子节点,先把他们链接起来,因为肯定是相邻的。
然后通过root的next指针,找到需要与当前节点子节点连接的后继节点。
因为涉及到root的next指针查询,递归需要先处理完右子树,以便左子树节点next指针的连接。
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
题意把二叉树每一层所有的节点顺序链接,只能开辟常数空间。
这题与上道题不同点在于二叉树不是完全二叉树,因此结构差别较大,不能用上道题的方法。
如果当前节点有左右子节点,先把他们链接起来,因为肯定是相邻的。
然后通过root的next指针,找到需要与当前节点子节点连接的后继节点。
因为涉及到root的next指针查询,递归需要先处理完右子树,以便左子树节点next指针的连接。
/** * 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; TreeLinkNode *temp=root->next,*p; if(root->left &&root->right) { p=root->right; root->left->next = root->right; } else if(root->right)p=root->right; else if(root->left)p=root->left; else p=NULL; if(p) { while(temp) { if(temp->left) { p->next = temp->left; break; } else if(temp->right) { p->next = temp->right; break; } else temp=temp->next; } } connect(root->right); connect(root->left); } }; // http://blog.csdn.net/havenoidea[/code]
题解目录
相关文章推荐
- 关于指针的一些事情
- 关于c语言指针的两处小tip分享
- 浅析iterator与指针的区别
- 探讨C++中数组名与指针的用法比较分析
- C++中指向对象的常指针与指向常对象的指针详解
- 指向变量的常指针与指向常变量的指针详细解析
- php中将指针移动到数据集初始位置的实现代码[mysql_data_seek]
- C语言指针学习经验总结浅谈
- C/C++中指针和引用之相关问题深入研究
- 指针与const限定符的使用分析
- c++ 指针与引用的区别介绍及使用说明
- c++函数中的指针参数与地址参数区别介绍
- javascript function、指针及内置对象
- (C和指针) #if 0/#if 1...#end if
- C++中用指向数组的指针作函数参数
- 关于《C和指针》的学习笔记
- 深入解析C++中的指针数组与指向指针的指针
- 指向类成员函数的指针其实并非指针
- 深入理解void以及void指针的含义
- C/C++指针和取地址的方法