3.30
即使昨天联系了半天的二叉树的基本操作,今天做起题目来依旧不顺手。
想着边遍历边修改左右子树,但是好像不太现实。
只好把先序遍历的结果存在queue中
然后再遍历queue,再修改子树。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void flatten(TreeNode root) {
if(root == null){
return;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode bt = root;
while(bt != null || !list.isEmpty()){// write your code here
while(bt != null){
//System.out.print(bt.val + " ");
queue.addLast(bt);
list.push(bt);
bt = bt.left;
}
if(!list.isEmpty()){
bt = list.pop();
//System.out.print(tmp.val + " ");
bt = bt.right;
}
}
//System.out.print("\n");
root = queue.pop();
bt = root;
//System.out.print("\n" + bt.val + " ");
while(!queue.isEmpty()){
bt.left = null;
bt.right = queue.getFirst();
bt = queue.pop();
//System.out.print(bt.val + " ");
}
bt.left =bt.right = null;
}
}