114. Flatten Binary Tree to Linked List(二叉树展开为链表)
程序员文章站
2022-05-21 19:18:06
...
题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
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
思路:先序遍历用list存储,再连接。
AC 1ms 99.6% Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<TreeNode> list=new ArrayList();
public void flatten(TreeNode root) {
if(root==null)
return;
helper(root);
TreeNode dummy=new TreeNode(0);
TreeNode p=dummy;
for(int i=0;i<list.size();i++){
p.left=null;
p.right=list.get(i);
p=p.right;
}
root=dummy.right;
}
public void helper(TreeNode root){
if(root==null)
return;
list.add(root);
helper(root.left);
helper(root.right);
}
}
推荐阅读
-
LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)
-
114. Flatten Binary Tree to Linked List(二叉树展开为链表)
-
【leetcode】114. 二叉树展开为链表(Flatten Binary Tree to Linked List)(DFS)
-
LeetCode: 114. Flatten Binary Tree to Linked List
-
114. Flatten Binary Tree to Linked List
-
LeetCode 114. Flatten Binary Tree to Linked List 二叉树展开为链表(Java)
-
leetcode题解(四十三):114. Flatten Binary Tree to Linked List
-
LeetCode·114. Flatten Binary Tree to Linked List
-
(M)DFS:114. Flatten Binary Tree to Linked List
-
114. Flatten Binary Tree to Linked List