[Leetcode]144. Binary Tree Preorder Traversal

本文介绍了解决LeetCode上二叉树前序遍历问题的两种方法:递归和迭代。递归方法通过深度优先搜索的方式,先访问根节点,再分别访问左子树和右子树;迭代方法则利用栈来实现同样的过程,避免了递归可能带来的堆栈溢出问题。

link: https://leetcode.com/problems/binary-tree-preorder-traversal/

Solution1: 使用递归

class Solution {
    public void helper(TreeNode root, List<Integer> res) {
        if(root != null) res.add(root.val);
        if(root.left != null) helper(root.left, res);
        if(root.right != null) helper(root.right, res);
    }
    
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null) return res;
        helper(root, res);
        return res;
        
    }
}

TC: O()

Solution2: 使用迭代

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack stack = new Stack();
        if(root == null) return res;
        
        while(root != null || !stack.empty()){
            if(root == null) {
                root = ((TreeNode)stack.pop()).right;
                continue;
            }
            res.add(root.val);
            stack.push(root);
            root = root.left;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值