二叉树展开为链表

LeetCode每日一题,114. Flatten Binary Tree to Linked List

先看题目描述

题目意思就是把二叉树展开为链表

算法和思路

可以看到展开的链表是按照先根遍历的顺序来的,这题第一反应就想到用递归,先将左子树展开为链表,再将右子树展开为链表,然后用一个临时变量存储右子树,再将根节点的左子树移到右子树上,同时令其左子树为空,最后将临时变量存储的原来右子树接到现在根节点右子树的最后一个节点上即可

算法源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
flatten(root.left);
flatten(root.right);
TreeNode temp = root.right;
root.right = root.left;
root.left = null;
while (root.right != null) {
root = root.right;
}
root.right = temp;
}
}