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;
    }
    
  • 相关阅读:
    Solr 规格严格
    createsimplepojoclassesbytecodeatruntimedynamically 规格严格
    Mongo 规格严格
    Java Classpath 规格严格
    ClassLoader 规格严格
    Lucene 规格严格
    封包和拆包
    NetBeans 时事通讯(刊号 # 25 Sep 11, 2008)
    安全注释和授权在 GlassFish 和 Java EE 5 SDK 中的应用
    Building Enterprise Applications for GlassFish using Netbeans IDE and Maven2
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/9668887.html
Copyright © 2011-2022 走看看