题目:binary-tree-preorder-traversal
方法一:
递归,因二叉树的子问题和原问题一样,所以用递归总能方便的解决问题。
代码如下:
import java.util.*;
public class Solution {
private ArrayList<Integer> array=new ArrayList();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
if(root == null)
return array;
array.add(root.val);
array=preorderTraversal(root.left);
array=preorderTraversal(root.right);
return array;
}
}
方法二:
非递归方法,用栈实现。
代码如下:
import java.util.*;
public class Solution {
private ArrayList<Integer> array=new ArrayList();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack=new Stack();
TreeNode node = root;
while(node!=null||!stack.empty())
{
while(node!=null)
{
array.add(node.val);
stack.push(node);
node=node.left;
}
if(node == null&&!stack.empty())
{
node=stack.pop().right;
}
}
return array;
}
}