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;
}
posted @ 2018-09-18 14:52  罗梁  阅读(1480)  评论(0编辑  收藏  举报