题目
原题页面:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
题目类型:Tree, Depth-first Search
难度评价:Medium
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
2
3
4
5 1
/ \
2 5
/ \ \
3 4 6The flattened tree should look like:
1
2
3
4
5
6
7
8
9
10
11 1
\
2
\
3
\
4
\
5
\
6Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
分析
题目的算法本身并不难理解,按照先序遍历的节点顺序将一棵二叉树拉平为一个“链表”。因此后序遍历二叉树,先将左子树“拉平”,再将右子树“拉平”,然后如果左子树不是None,就将已经拉平为“链表”的左子树,嵌入到当前节点与直接右孩子节点(可能右孩子是None)之间。关键在于一些分支上要判断是否不为None,很容易出错。
代码
1 | class Solution: |
本文地址:https://xnerv.wang/leetcode-flatten-binary-tree-to-linked-list/
