Flatten Binary Tree to Linked List ——LeetCode

时间:2023-03-08 22:23:09

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
/ \
2 5
/ \ \
3 4 6

The flattened tree should look like:

   1
\
2
\
3
\
4
\
5
\
6

题目大意:给一个二叉树,将它转为一个list,转换后的序列应该是先序遍历,list由这棵树的右孩子表示。

解题思路:递归的处理左子树,然后处理右子树,将左孩子的右孩子置为当前节点的右孩子,然后将当前节点的右孩子置为左孩子。

    public void flatten(TreeNode root) {
doFlat(root);
} private void doFlat(TreeNode node) {
if (node == null) {
return;
} doFlat(node.left);
if (node.left!=null) {
TreeNode tmp = node.left;
while(tmp.right!=null){
tmp=tmp.right;
}
tmp.right = node.right;
node.right = node.left;
node.left = null;
}
doFlat(node.right);
}