【力扣-数据结构】【第 10 天】144. 二叉树的前序遍历

标题144. 二叉树的前序遍历
难度简单
天数第10天,第1/3题
数据结构

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

示例 1:

在这里插入图片描述

输入:root = [1,null,2,3]
输出:[1,2,3]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

示例 4:

在这里插入图片描述

输入:root = [1,2]
输出:[1,2]

示例 5:

在这里插入图片描述

输入:root = [1,null,2]
输出:[1,2]

提示:

  • 树中节点数目在范围 [0, 100]
  • -100 <= Node.val <= 100

进阶:递归算法很简单,你可以通过迭代算法完成吗?

以上内容来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

  1. 前序遍历,前序遍历首先访问根结点然后遍历左子树,最后遍历右子树。
  2. 我们利用Stack先进后出的特性,来遍历我们的树
	Stack<TreeNode> stack = new Stack<TreeNode>();
  1. 创建res用于存储返回数据
	List<Integer> res  = new ArrayList();
  1. 先判断树是否为空,如果是空树直接返回空list
	if(root == null){
		return res;
	}
  1. 将数添加进栈stack中
	//树放入栈中
	stack.push(root);
  1. 循环遍历栈,如果栈空了停止循环
 	while(!stack.isEmpty()){
		xxxxx
	}
  1. 循环中 我们先取出树
    • 根节点添加到list中
    • 如果右树存在,右树先添加进栈中
    • 然后左树存在,左树添加进栈中
    • 这样下次循环,就先开始从左树中开始遍历赋值
 	TreeNode node = stack.pop();
	res.add(node.val);
	if(node.right != null){
		stack.push(node.right);
	}
	if(node.left != null){
		stack.push(node.left);
	}

完整代码:

/**
 * 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 {
    //数据结构  第 10 天 1/3 树
    public List<Integer> preorderTraversal(TreeNode root) {
        //用于存储遍历的数据
        List<Integer> res  = new ArrayList();
        //利用栈先进后出的特性,达到我们前序遍历目的
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if(root == null){
            return res;
        }
        //树放入栈中
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            res.add(node.val);
            if(node.right != null){
                stack.push(node.right);
            }
            if(node.left != null){
                stack.push(node.left);
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Crazy丶code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值