C++實現(xiàn)LeetCode(114.將二叉樹展開成鏈表)
[LeetCode] 114. Flatten Binary Tree to Linked List 將二叉樹展開成鏈表
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order trave
這道題要求把二叉樹展開成鏈表,根據(jù)展開后形成的鏈表的順序分析出是使用先序遍歷,那么只要是數(shù)的遍歷就有遞歸和非遞歸的兩種方法來求解,這里我們也用兩種方法來求解。首先來看遞歸版本的,思路是先利用 DFS 的思路找到最左子節(jié)點,然后回到其父節(jié)點,把其父節(jié)點和右子節(jié)點斷開,將原左子結點連上父節(jié)點的右子節(jié)點上,然后再把原右子節(jié)點連到新右子節(jié)點的右子節(jié)點上,然后再回到上一父節(jié)點做相同操作。代碼如下:
解法一:
class Solution {
public:
void flatten(TreeNode *root) {
if (!root) return;
if (root->left) flatten(root->left);
if (root->right) flatten(root->right);
TreeNode *tmp = root->right;
root->right = root->left;
root->left = NULL;
while (root->right) root = root->right;
root->right = tmp;
}
};
例如,對于下面的二叉樹,上述算法的變換的過程如下:
1
/ \
2 5
/ \ \
3 4 6
1
/ \
2 5
\ \
3 6
\
4
1
\
2
\
3
\
4
\
5
\
6
下面再來看非迭代版本的實現(xiàn),這個方法是從根節(jié)點開始出發(fā),先檢測其左子結點是否存在,如存在則將根節(jié)點和其右子節(jié)點斷開,將左子結點及其后面所有結構一起連到原右子節(jié)點的位置,把原右子節(jié)點連到元左子結點最后面的右子節(jié)點之后。代碼如下:
解法二:
class Solution {
public:
void flatten(TreeNode *root) {
TreeNode *cur = root;
while (cur) {
if (cur->left) {
TreeNode *p = cur->left;
while (p->right) p = p->right;
p->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
cur = cur->right;
}
}
};
例如,對于下面的二叉樹,上述算法的變換的過程如下:
1
/ \
2 5
/ \ \
3 4 6
1
\
2
/ \
3 4
\
5
\
6
1
\
2
\
3
\
4
\
5
\
6
前序迭代解法如下:
解法三:
class Solution {
public:
void flatten(TreeNode* root) {
if (!root) return;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode *t = s.top(); s.pop();
if (t->left) {
TreeNode *r = t->left;
while (r->right) r = r->right;
r->right = t->right;
t->right = t->left;
t->left = NULL;
}
if (t->right) s.push(t->right);
}
}
};
此題還可以延伸到用中序,后序,層序的遍歷順序來展開原二叉樹,分別又有其對應的遞歸和非遞歸的方法,有興趣的童鞋可以自行實現(xiàn)。
Github 同步地址:
https://github.com/grandyang/leetcode/issues/114
類似題目:
Flatten a Multilevel Doubly Linked List
參考資料:
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
到此這篇關于C++實現(xiàn)LeetCode(114.將二叉樹展開成鏈表)的文章就介紹到這了,更多相關C++實現(xiàn)將二叉樹展開成鏈表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
c語言之char*和unsigned?char*的區(qū)別及說明
這篇文章主要介紹了c語言之char*和unsigned?char*的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
C語言中回調(diào)函數(shù)和qsort函數(shù)的用法詳解
這篇文章主要為大家詳細介紹一下C語言中回調(diào)函數(shù)和qsort函數(shù)的用法教程,文中的示例代碼講解詳細,對我們學習C語言有一定幫助,需要的可以參考一下2022-07-07
C++實現(xiàn)CreatThread函數(shù)主線程與工作線程交互的方法
這篇文章主要介紹了C++實現(xiàn)CreatThread函數(shù)主線程與工作線程交互的方法,是Windows應用程序設計中非常實用的方法,需要的朋友可以參考下2014-10-10

