Given a binary tree, return the preorder traversal of its nodes' values.
For example:Given binary tree{1,#,2,3},
1
\
2
/
3
return[1,2,3].
二叉树的前序遍历
解法一:递归
import java.util.ArrayList;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer>a=new ArrayList<Integer>();
if (root==null)
return a;
a.add(root.val);
a.addAll(preorderTraversal(root.left));
a.addAll(preorderTraversal(root.right));
return a;
}
}
解法二:迭代
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer>a=new ArrayList<Integer>();
if (root==null)
return a;
Stack<TreeNode>stack1=new Stack<TreeNode>();
Queue<TreeNode>queue=new LinkedList<TreeNode>();
stack1.push(root);
while (!stack1.empty())
{
TreeNode t=stack1.pop();
if (t.right!=null)
stack1.push(t.right);
if (t.left!=null)
stack1.push(t.left);
queue.offer(t);
}
while (!queue.isEmpty())
{
a.add(queue.poll().val);
}
return a;
}
}
网友评论