题目链接: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);
}
}