Flatten Binary Tree to Linked List
2016-02-28 13:04
330 查看
Given a binary tree, flatten it to a linked list in-place.For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6 利用前序遍历解决的方法实现
void flatten(TreeNode* root) { if (root == nullptr) return; stack<TreeNode*> sta; sta.push(root); TreeNode* lastRoot = root; while (!sta.empty()) { root = sta.top(); if (lastRoot != root->right) { if (lastRoot != root->left) { if (root->left != nullptr) { sta.push(root->left); continue; } } else { TreeNode* tempNode = root->right; root->right = lastRoot; root->left = nullptr; TreeNode* endNode = lastRoot; while (endNode->right != nullptr) endNode = endNode->right; endNode->right = tempNode; } if (root->right != nullptr) { sta.push(root->right); continue; } } lastRoot = root; sta.pop(); } }不使用遍历的方法,即不使用栈解决的方法
void flatten(TreeNode *root) { TreeNode*now = root; while (now) { if (now->left) { //Find current node's prenode that links to current node's right subtree TreeNode* pre = now->left; while (pre->right) { pre = pre->right; } pre->right = now->right; //Use current node's left subtree to replace its right subtree(original right //subtree is already linked by current node's prenode now->right = now->left; now->left = NULL; } now = now->right; } }
相关文章推荐
- ubuntu安装python
- 【Codeforces Round 340 (Div 2)C】【暴力排序枚举】Watering Flowers 2个灌溉器灌溉所有点最小的rr+RR
- [效率神技]Intellij 的快捷键和效率技巧|系列一|常用快捷键
- 大型网站架构系列:负载均衡详解(2)
- Database Replay wrc命令报错ORA-15552: workload replay client cannot login to database server
- Manthan, Codefest 16 E. Startup Funding ST表 二分 数学
- 自定义dialog类
- genymotion无法下载解决方法
- 【Codeforces Round 340 (Div 2)B】【简单题】Chocolate 巧克力划分方案数 每段恰有一个坚果
- java重拍 https://www.zhihu.com/question/34387716/answer/76029594
- Uiautomator编译运行的自动化
- SDK无法更新
- andorid build tools 19.1
- LeetCode OJ 1. Two Sum
- mySql乱码
- visualSVN server库迁移
- 大型网站架构系列:负载均衡详解(1)
- 【Codeforces Round 340 (Div 2)A】【水题】Elephant
- android之DPAD上下左右四个键控制
- Ubuntu 12.04 硬盘安装