<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">思路:順序爲前序遍歷的順序</span>
需要注意的地方是需要對初始的root做修改而不是返回新的root。
public void flatten(TreeNode root)
這裏傳入的root只是指向root的指針,如果root=new TreeNode(val),root就不再指向root了。因此修改初始的root的話,需要修改root的值以及root的子節點,而不是將root指向一個新的節點。
TreeNode root=new TreeNode(val);
flatten(root)
此時函數外核函數內的root其實是兩個指針,都指向root。
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by marsares on 15/6/16.
*/
public class FlattenBinaryTreetoLinkedList {
Queue<Integer>queue=new LinkedList<Integer>();
public void flatten(TreeNode root) {
if(root==null)return;
traversal(root);
TreeNode current=root;
while(!queue.isEmpty()){
current.val=queue.poll();
current.left=null;
if(current.right==null&&!queue.isEmpty())current.right=new TreeNode(0);
current=current.right;
}
}
private void traversal(TreeNode root){
if(root==null)return;
queue.add(root.val);
traversal(root.left);
traversal(root.right);
}
public static void main(String[]args){
FlattenBinaryTreetoLinkedList fbtl=new FlattenBinaryTreetoLinkedList();
BinaryTreeSerialize bts=new BinaryTreeSerialize();
TreeNode root=bts.Unserialize("{1,2,5,3,4,6}");
fbtl.flatten(root);
System.out.println(bts.Serialize(root));
}
}