3.31
以为很简单,果然就大意了。
LinkedList 的 add 和push 还是有很大差别的啊。
还有add 和offer原来也是有一些差别的。
受教了呢。
/**
* 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: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
LinkedList<TreeNode> s = new LinkedList<TreeNode>();
if(root == null){
return list;
}// write your code here
TreeNode bt = root;
while( bt != null || !s.isEmpty()){
while( bt != null){
// s.add(root);
list.add(bt.val);
s.push(bt);
bt = bt.left;
}
if( !s.isEmpty()){
bt = s.pop();
bt = bt.right;
}
}
return list;
}
}