Leetcode:Flatten Binary Tree to Linked List 解题报告

时间:2023-03-09 06:26:29
Leetcode:Flatten Binary Tree to Linked List  解题报告

Flatten Binary Tree to Linked List

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
Leetcode:Flatten Binary Tree to Linked List  解题报告
SOLUTION 1:

使用递归解决,根据left是否为空,先连接left tree, 然后再连接右子树。使用一个tail 来记录链的结尾。在递归之前,先将root.left,root.right保存下来。
 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
dfs(root);
} // return : the tail of the list.
public TreeNode dfs(TreeNode root) {
if (root == null) {
return null;
} TreeNode left = root.left;
TreeNode right = root.right; // Init the root.
root.left = null;
root.right = null; TreeNode tail = root; // connect the left tree.
if (left != null) {
tail.right = left;
tail = dfs(left);
} // connect the right tree.
if (right != null) {
tail.right = right;
tail = dfs(right);
} return tail;
}
}