题目来源:leetcode
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].
思路:dfs递归(题目简单不要脸)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res=new ArrayList<>();
if (root==null)
return res;
dfs(res,root);
return res;
}
public void dfs(ArrayList<Integer> ls,TreeNode root){
ls.add(root.val);
if (root.left!=null)
dfs(ls,root.left);
if (root.right!=null)
dfs(ls,root.right);
}
}
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ls=new ArrayList<Integer>();
if(root==null)
return ls;
dfs(ls,root);
return ls;
}
public void dfs(List<Integer> ls,TreeNode root){
if(root.left!=null)
dfs(ls,root.left);
ls.add(root.val);
if(root.right!=null)
dfs(ls,root.right);
}
}