leet 114二叉樹展開為連結串列
阿新 • • 發佈:2020-07-09
解析直接複製官方解釋了,參考的第一種思路。自己沒想出來啊嗚嗚
1 / \ 2 5 / \ \ 3 4 6 //將 1 的左子樹插入到右子樹的地方 1 \ 2 5 / \ \ 3 4 6 //將原來的右子樹接到左子樹的最右邊節點 1 \ 2 / \ 3 4 \ 5 \ 6 //將 2 的左子樹插入到右子樹的地方 1 \ 2 \ 3 4 \ 5 \ 6 //將原來的右子樹接到左子樹的最右邊節點 1 \ 2 \ 3 \ 4 \5 \ 6 ...... 作者:windliang 連結:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--26/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。
然後用C++實現瞭如下
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * };*/ class Solution { public: void flatten(TreeNode* root) { while(root!=NULL) { if(root->left==NULL) { root=root->right; } else { TreeNode* pre=root->left; while(pre->right!=NULL) { pre=pre->right; } pre->right=root->right; root->right=root->left; root->left=NULL; root=root->right; } } } };