Leetcode中几道二叉树题 III
来源:互联网 发布:qq人肉搜索软件 编辑:程序博客网 时间:2024/06/05 02:21
三、树的层次/序列化
题目一:Populating Next Right Pointers in Each Node
Given a binary tree, populating each next pointer to pointer to its 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.
思路:必须通过层次访问二叉树,建立每一层节点之间的连接。
class Solution {public: void connect(TreeLinkNode *root) { if(root==NULL) return; vector<TreeLinkNode*> q; q.push_back(root); int cur=0; while(cur<q.size()){ int last=q.size(); while(cur<last){ if(cur<last-1){ q[cur]->next=q[cur+1]; } else q[cur]->next=NULL; if(q[cur]->left) q.push_back(q[cur]->left); if(q[cur]->right) q.push_back(q[cur]->right); cur++; } } }};
题目二: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?
思路:对解题方法没有任何影响。
题目三:Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place. Hints: if you notice carefully in the flattened tree, each node's right child pointers to the next node of a pre-order traversal.
思路1:因为是跟先序遍历与关系,那么只需要改造先序遍历,即可得到一个解。
class Solution {public: void flatten(TreeNode *root) { if(root==NULL) return; last=NULL; preOrderFlatten(root); } void preOrderFlatten(TreeNode *root){ if(root==NULL) return; TreeNode *savedRight=root->right; //先保存根节点的右孩子节点 if(last==NULL) last=root; else{ last->right=root; last->left=NULL; } last=root; preOrderFlatten(root->left); preOrderFlatten(savedRight); //由于遍历改变root->right的值,故这里需先保存 }private: TreeNode *last; //保存上次访问的节点};说明:这种解法不同与一般的遍历,因为它在遍历中改变了数的结构,因此需要提前保存好被改变的部分!
思路2:原题实质要求的是in-place解法,所以上面的解法并不是很符合要求,因此还得使用一般的“模拟”遍历。
class Solution {public: void flatten(TreeNode *root) { if(root==NULL) return; while(root){ if(root->left){ TreeNode *rightMost=root->left; while(rightMost->right) rightMost=rightMost->right; rightMost->right=root->right; root->right=root->left; //事先已经保存好了 root->left=NULL; } root=root->right; } }};
- Leetcode中几道二叉树题 III
- LeetCode 437. Path Sum III 题解 和固定的二叉树路径数目
- [LeetCode]437. Path Sum III(求二叉树中路径和等于sum的数量)
- Leetcode中几道二叉树题 I
- Leetcode中几道二叉树题 II
- Leetcode中几道二叉树题 (IV)
- leetcode_437. Path Sum III-二叉树
- LeetCode二叉树基础题(不断更新)
- leetcode:构建二叉树
- 重建二叉树 leetcode
- LeetCode -- Flatten 二叉树
- leetcode-构造二叉树
- leetcode二叉树遍历
- leetcode 重建二叉树
- 二叉树题目-leetcode
- LeetCode:反转二叉树
- [leetcode]二叉树遍历
- LeetCode二叉树合并
- 求类似aabb形式的完全平方数
- CSS BUG顺口溜,快速牢记CSS的Bug处理方法
- Java.lang.Character类学习
- 浅谈.NET中的数据绑定表达式
- 3D数学读书笔记——向量运算及在c++上的实现
- Leetcode中几道二叉树题 III
- 桥接模式
- xcode 中#pragma的使用
- errors were encountered while processing qmail qmail-run
- 07.实例篇:ListView简单分页加载-ListView从网络分页加载数据
- (三)利用导入表、导出表和重定位表定位导入函数的地址
- 3D数学读书笔记——矩阵基础
- ThinkPad E420 中ctrl+alt+down 快捷键与eclipse快捷键冲突解决办法
- 颜色矩