LeetCode.144. 二叉树的前序遍历

题目

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

    void func(TreeNode cur,List<Integer> res) {
        if(cur == null) return;
        // 先记录根节点
        res.add(cur.val);
        // 遍历左子树
        func(cur.left,res);
        // 遍历右子树
        func(cur.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<>();
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
        while(!s.isEmpty()) {
            TreeNode node = s.pop();
            if(node != null) {
                res.add(node.val);
                
            }else {
                continue;
            }
            s.push(node.right);
            s.push(node.left);
        }
        return res;
    }

 
}
相关推荐
¥ 多多¥1 小时前
数据结构:内存的使用
linux·c语言·开发语言·数据结构
EPSDA1 小时前
Java的IO流(二)
java·开发语言
小灰灰爱代码1 小时前
C++——将数组a[5]={-1,2,9,-5,7}中小于0的元素置成0。并将其结果输出(要求:用数组名作为函数的参数来实现)
数据结构·c++·算法
zzlyyds2 小时前
SpringBoot---------Actuator监控
java·spring boot·spring·actuator
vitobo2 小时前
Java的JDBC编程
java·开发语言
呆萌小新@渊洁2 小时前
后端接收数组,集合类数据
android·java·开发语言
Mopes__3 小时前
Python | Leetcode Python题解之第421题数组中两个数的最大异或值
python·leetcode·题解
A_cot3 小时前
深入了解 Maven 和 Redis
java·redis·maven
liuyang-neu3 小时前
力扣中等 33.搜索旋转排序数组
java·数据结构·算法·leetcode
爱吃烤鸡翅的酸菜鱼3 小时前
java(3)数组的定义与使用
java·开发语言·idea·intellij idea