竟然超时了T_T
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution{
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode p = null;
if(root == null){
return list;
}
list.add(root.val);
stack.push(root);
while(!stack.isEmpty()){
while((p = stack.peek()).left != null){
stack.push(p);
list.add(p.val);
}
while(!stack.isEmpty() && (p = stack.peek()).right == null){
stack.pop();
}
if(p.right != null){
<span style="white-space:pre"> </span>stack.push(p.right);
list.add(p.right.val);
}
}
return list;
}
}
那就换一种方法:
先存右节点,再存左节点;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = null;
if(root == null){
return list;
}
stack.push(root);
while(!stack.isEmpty()){
p = stack.peek();
list.add(p.val);
stack.pop();
if(p.right != null){
stack.push(p.right);
}
if(p.left != null){
stack.push(p.left);
}
}
return list;
}
}