版權聲明:本文為博主原創(chuàng)文章故硅,未經博主允許不得轉載金矛。
難度:容易
要求:
給出一棵二叉樹,返回其節(jié)點值的前序遍歷感帅。
樣例給出一棵二叉樹
{1,#,2,3}
1
\
2
/
3
返回 [1,2,3]
思路:非遞歸
/**
* 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) {
// write your code here
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(node != null || stack.size() > 0){
if(node != null){
list.add(node.val);//壓棧之前先訪問
stack.push(node);//將所有左孩子壓棧
node = node.left;
}else{
node = stack.pop();
node = node.right;
}
}
return list;
}
}
思路:遞歸
/**
* 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> result = new ArrayList<Integer>();
traverse(root, result);
return result;
}
// 把root為跟的preorder加入result里面
private void traverse(TreeNode root, ArrayList<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
traverse(root.left, result);
traverse(root.right, result);
}
}