思路:前序遍历存储之后,然后令root的左右子树为null,再在root结点的右子树上边创建结点,边把存储的数往里面填。
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {List<Integer>list=new ArrayList<>();public void flatten(TreeNode root) {if(root==null)return;qianxu(root);root.left=null;root.right=null;for(int i=1;i<list.size();i++){root.right=createNode(root.right,list.get(i));root=root.right;}}public TreeNode createNode(TreeNode t,int val){if(t==null){TreeNode tmp=new TreeNode();tmp.val=val;return tmp;}return null;}public void qianxu(TreeNode t){if(t==null){return;}list.add(t.val);qianxu(t.left);qianxu(t.right);}
}