binary-tree-preorder-traversal

题目描述

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].
Note: Recursive solution is trivial, could you do it iteratively?

思路

递归遍历

代码

/**
 * 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>  result = new ArrayList<>();
        preOrderTraversalCore(result,root);
        return result;
    }
    private void preOrderTraversalCore(ArrayList<Integer>  result,TreeNode root){
        if(root == null) return;
        result.add(root.val);
        preOrderTraversalCore(result,root.left);
        preOrderTraversalCore(result,root.right);
    }
}