LeetCode 114. 二叉树展开为链表
思路:
如果,当前结点存在左儿子,就找到左子树中的最右的叶子结点,然后把叶子结点的右儿子更新为root->right,然后把root->right 更新为root的左儿子。
代码:
/**
* 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){
auto p=root->left;
if(p){
while(p->right) p = p->right;
p->right=root->right;
root->right = root->left;
root->left = nullptr;
}
root = root->right;
}
}
};
评论区