0%

flatten-binary-tree-to-linked-list

题目描述

给定一个二叉树,原地将它展开为链表。

题解

永远都是两类:自顶向下和自底向上。

注意后面要把左子树赋值为NULL,不然递归还会进到左子树。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void flatten(TreeNode* root) {
if (!root)return;
if (!root->left) {
flatten(root->right);
return;
}
flatten(root->left);
flatten(root->right);
TreeNode* t1 = root->left;
while (t1->right)t1 = t1->right;
t1->right = root->right;
root->right = root->left;
root->left = NULL;
}