LeetCode 114. 二叉树展开为链表
原题链接
中等
作者:
linux_2019
,
2019-07-29 10:43:40
,
所有人可见
,
阅读 881
C++ 代码
/**
* 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 dfs(TreeNode * root)
{
if(!root) return;
dfs(root->left);
dfs(root->right);
if(root->left)
{
TreeNode * tmp=root->right;
root->right=root->left;
root->left=NULL;
TreeNode *right=root->right;
TreeNode *pre=root->right;
while(right)
{
pre=right;
right=right->right;
}
pre->right=tmp;
}
}
void flatten(TreeNode* root) {
dfs(root);
}
};