114 Flatten Binary Tree to Linked List 二叉樹轉換鏈表
阿新 • • 發佈:2018-04-05
eno 二叉樹 int 方法 ini rip binary right script
給定一個二叉樹,使用原地算法將它 “壓扁” 成鏈表。
示例:
給出:
1
/ \
2 5
/ \ \
3 4 6
壓扁後變成如下:
1
\
2
\
3
\
4
\
5
\
6
提示:
如果您細心觀察該扁平樹,則會發現每個節點的右側子節點是以原二叉樹前序遍歷的次序指向下一個節點的。
詳見:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
方法一:遞歸解法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { if(root==nullptr) { return; } if(root->left) { flatten(root->left); } if(root->right) { flatten(root->right); } TreeNode *tmp=root->right; root->right=root->left; root->left=nullptr; while(root->right) { root=root->right; } root->right=tmp; } };
方法二:非遞歸解法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { if(root==nullptr) { return; } 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=nullptr; } cur=cur->right; } } };
參考:https://www.cnblogs.com/grandyang/p/4293853.html
114 Flatten Binary Tree to Linked List 二叉樹轉換鏈表