[leetcodeブラシ問題シリーズ]Flatten Binary Tree to Linked List
1153 ワード
シミュレーション問題ですが、このタイプの問題は確かに見たことがありません.またポインタを練習しました:)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode * dfs(TreeNode * root){
if(root->left != 0){
TreeNode * last_left = dfs(root->left);
if(root->right == 0){
root->right = root->left;
root->left = 0;
return last_left;
}else{
TreeNode * last_right = dfs(root->right);
last_left->right = root->right;
root->right = root->left;
root->left = 0;
return last_right;
}
}
if(root->right != 0)
return dfs(root->right);
return root;
}
public:
void flatten(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == 0)
return ;
dfs(root);
}
};