[LeetCode] Flatten Binary Tree to Linked List
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Flatten Binary Tree to Linked List
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1/ \2 5/ \ \ 3 4 6The flattened tree should look like:
1\2\3\4\5\6將一個二叉樹重組成一個鏈表
題目要求按照二叉樹的先序遍歷的順序重組二叉樹
思路1:
找到最左側結點,將其父結點與父結點右結點斷開,將其連接至父結點右側,變成父結點的右結點,然后把原右結點插入到新右結點的右側。遞歸這一操作即可
/*** 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)return;if (root->left)flatten(root->left);if (root->right)flatten(root->right);TreeNode* temp = root->right;root->right = root->left;root->left = NULL;while (root->right)root = root->right;root->right = temp;} };思路2:
從根結點出發,判斷其左結點是否存在,如果存在,則將根結點與其右結點斷開,根的左結點變成其右結點。在將右結點鏈接至左結點最右邊的右結點處。
/*** 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)return;TreeNode* curr = root;while (curr){if (curr->left){TreeNode* temp = curr->left;while (temp->right)temp = temp->right;temp->right = curr->right;curr->right = curr->left;curr->left = NULL;}curr = curr->right;}} };?
轉載于:https://www.cnblogs.com/immjc/p/9076162.html
總結
以上是生活随笔為你收集整理的[LeetCode] Flatten Binary Tree to Linked List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: P2014 选课 (树形动规)
- 下一篇: hdu4035 Maze 【期望dp