LeetCode 144. Binary Tree Preorder Traversal--二叉树前序遍历--反向压栈--迭代-栈,递归--C++,Python解法

这篇博客介绍了LeetCode上的144题——二叉树前序遍历。首先,提供了递归解法的Python实现,接着详细阐述了如何使用迭代方法,借助栈来完成前序遍历,并给出了相应的Python和C++代码。最后,指出迭代解法的时间复杂度为O(n),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:Binary Tree Preorder Traversal - LeetCode


Given a binary tree, return the preorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?


经典的二叉树前续遍历,递归解法最容易想到。
Python解法如下:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        def helper(root, l):
            if root is None:
                return
            l.append(root.val)
            helper(root.left,l)
            helper(root.right,l) 
        l = []
        helper(root, l)
        return l

迭代的解法要复杂一些,要用到栈。

Python解法如下:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        l = []
        if root is None:
            return l
        stack=[root]
        while stack!=[]:
            temp=stack.pop()
            if temp is not None:
                l.append(temp.val)
                if temp.right is not None:
                    stack.append(temp.right)
                if temp.left is not None:
                    stack.append(temp.left)
        return l

时间复杂度为O(n),空间复杂度为O(1)。

C++解法如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> result;
        stack<TreeNode *> l;
        l.push(root);
        while (!l.empty()) {
            TreeNode *temp = l.top();
            l.pop();
            if (temp == nullptr) {
                continue;
            }
            result.push_back(temp->val);
            if (temp->right != nullptr) {
                l.push(temp->right);
            }
            if (temp->left != nullptr) {
                l.push(temp->left);
            }
        }
        return result;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值