-
Notifications
You must be signed in to change notification settings - Fork 0
/
114.二叉树展开为链表.cpp
45 lines (42 loc) · 1.08 KB
/
114.二叉树展开为链表.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* @lc app=leetcode.cn id=114 lang=cpp
*
* [114] 二叉树展开为链表
*/
// @lc code=start
/**
* 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) {
if(root == nullptr) return;
DFS(root);
}
private:
void DFS(TreeNode* root){
if(root->left != nullptr){
DFS(root->left);
}
if(root->right != nullptr){
DFS(root->right);
}
if(root->left != nullptr){
auto t = root->right;
root->right = root->left;
auto rightNode = root->right;
while(rightNode->right != nullptr) rightNode = rightNode->right;
rightNode->right = t;
root->left = nullptr;
}
}
};
// @lc code=end