题解 | #二叉树的前序遍历#

二叉树的前序遍历

https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public int[] preorderTraversal (TreeNode root) {
        ArrayList<Integer> arr=new ArrayList<>();
        preorder(root,arr);
        int[] num=new int[arr.size()];
        for(int i=0;i<arr.size();i++){
            num[i]=arr.get(i);
        }
        return num;
    }
    private void preorder(TreeNode root,ArrayList<Integer> arr){
        if(root==null){
            return;
        }
        arr.add(root.val);
        preorder(root.left,arr);
        preorder(root.right,arr);
    }
}

全部评论

相关推荐

每晚夜里独自颤抖:把华北改为华南再试一试,应该就没啥问题了。改完可能都不用投,别人主动联系了。
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务