原题地址:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/description/
题目描述:
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
解题方案:
使用递归,代码量就很少了。。
深度优先遍历,先左后右。
/**
* 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 flatten(TreeNode* root) {
if(!root)
return;
TreeNode* pre = root->left;
flatten(root->left);
flatten(root->right);
if(pre){
while(pre->right) pre = pre->right;
pre->right = root->right;
root->right = root->left;
root->left = NULL;
}
}
};