zoukankan      html  css  js  c++  java
  • Leetcode:二叉树的前序遍历

    Leetcode: 二叉树的前序遍历


    最近在复习数据结构, 感觉很多东西都忘得的差不多了,哪怕是看完书再看视频,还是容易忘,所以干脆想着配合leetcode来刷吧,Python实现起来很简单,但是C语言也不能丢,所以C语言和Python一起吧。

    题目:
    给定一个二叉树,返回它的前序遍历。

    输入: [1,null,2,3]  
       1
        
         2
        /
       3 
    
    输出: [1,2,3]
    

    Python 实现

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            result = []
            stack = [root]
            while len(stack):
                root = stack.pop()
                while root:
                    result.append(root.val) # 访问
                    stack.append(root.right) # 把右孩子加入栈中
                    root = root.left # 继续向左走
            return result
                
    

    C语言实现

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* preorderTraversal(struct TreeNode* root, int* returnSize) {
        int *result = (int *)malloc(sizeof(int) * 100);
        struct TreeNode *stack[1000]; // 用数组替代栈
        int top = -1;
        stack[++top] = root;
        int i = 0;
        while(top != -1){
            root = stack[top--]; // 弹出栈顶
            while(root){
                result[i++] = root->val;
                stack[++top] = root->right;
                root = root->left;
            }
        }
        *returnSize = i;
        return result;
    }
    
  • 相关阅读:
    人工智能-实验一策略迭代和值迭代
    Lecture 3: Planning by Dynamic Programming
    Lecture 2: Markov Decision Processes
    Software Testing -- LAB02-Selenium上机实验
    数据结构-王道2017-第4章 树与二叉树-二叉树的遍历
    数据结构-王道2017-第4章 树与二叉树
    PHP-基础知识
    nginx的安装与配置
    在Linux上部署项目
    zk 命令
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/9668887.html
Copyright © 2011-2022 走看看