Leetcode:二叉樹的前序遍歷
阿新 • • 發佈:2018-12-10
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; }