Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
思路:
通过递归遍历二叉树,发现二叉树有左子树时将左子树插入根节点和右子树之间。
void flatten(TreeNode* root) {
if (!root) return;
if (root->left){
flatten(root->left);
TreeNode* oldRight = root->right, *currRight = root->left;
root->right = root->left;
while (currRight->right) currRight = currRight->right;
currRight->right = oldRight;
root->left = NULL;
}
flatten(root->right);
}
纪念贴图:
在这里说明一下,如果你想要运行时间在某个阶段的代码,可以单击柱状图来查看,如下图: