Leetcode-144 二叉树的前序遍历

递归方法

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<Integer>();
        accessTree(root,res);
        return res;
    }

    public void accessTree(TreeNode root,List res){
        if(root==null){
            return;
        }
        res.add(root.val);
        accessTree(root.left,res);
        accessTree(root.right,res);
    }
}

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<Integer>();
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        while(!stack.isEmpty()||root!=null){
            while(root!=null){
                res.add(root.val);
                stack.push(root);
                root=root.left;
            }
            root=stack.pop();
            root=root.right;
        }
        return res;
    }
}
相关推荐
消失的旧时光-19438 分钟前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
毕设源码-朱学姐13 分钟前
【开题答辩全过程】以 4S店汽车维修保养管理系统为例,包含答辩的问题和答案
java·spring boot·汽车
Gu_shiwww24 分钟前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
盖世英雄酱581361 小时前
Read timed out问题 排查
java·数据库·后端
狼爷1 小时前
破解 JetBrains 的学生,后来都成了它的 “推销员”:一场用习惯换市场的长期战
java·jetbrains
你怎么知道我是队长1 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒1 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
.豆鲨包1 小时前
【Android】Viewpager2实现无限轮播图
android·java
BXCQ_xuan1 小时前
软件工程实践二:Spring Boot 知识回顾
java·spring boot·后端
老赵的博客1 小时前
c++ unqiue指针
java·jvm·c++