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
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
TreeNode p=root;
List<TreeNode> list=PreOrder(root); for(int i=1;i<list.size();i++)
{
p.right=list.get(i);
p.left=null;
p=p.right;
} }
public List<TreeNode> PreOrder(TreeNode root){//树的前序遍历
List<TreeNode> list=new ArrayList<>();
try{
list.add(root); if(root.left!=null)
list.addAll(PreOrder(root.left));
if(root.right!=null)
list.addAll(PreOrder(root.right));
}catch(NullPointerException e){}
return list;
}
}