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
代碼如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public void flatten(TreeNode root) { 12 TreeNode p=root; 13 List<TreeNode> list=PreOrder(root); 14 15 for(int i=1;i<list.size();i++) 16 { 17 p.right=list.get(i); 18 p.left=null; 19 p=p.right; 20 } 21 22 } 23 public List<TreeNode> PreOrder(TreeNode root){//樹的前序遍歷 24 List<TreeNode> list=new ArrayList<>(); 25 try{ 26 list.add(root); 27 28 if(root.left!=null) 29 list.addAll(PreOrder(root.left)); 30 if(root.right!=null) 31 list.addAll(PreOrder(root.right)); 32 }catch(NullPointerException e){} 33 return list; 34 } 35 }