LeetCode 144.二叉树的前序遍历

题目 :给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

思路:根 左 右

代码

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dfs(res, root);
        return res;
    }
    private void dfs(List<Integer> res, TreeNode root) {
        if (root == null)
            return;
        res.add(root.val);
        dfs(res, root.left);
        dfs(res, root.right);
    }
}

性能

时间复杂度o(n)

空间复杂度o(n)

相关推荐
不会就选b30 分钟前
算法日常・每日刷题--<贪心>14
算法
mmmmath_33 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z3 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧4 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背5 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝5 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
参.商.5 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
HZZD_HZZD5 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl7 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法