码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:二叉树的前序遍历

时间:2018-09-18 16:11:51      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:sizeof   not   ret   traversal   returns   binary   pop   list   array   

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;
}

Leetcode:二叉树的前序遍历

标签:sizeof   not   ret   traversal   returns   binary   pop   list   array   

原文地址:https://www.cnblogs.com/xmxj0707/p/9668887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!