leetcode144.二叉树的前序遍历

简介: leetcode144.二叉树的前序遍历

题目链接

1.png

2.png

二叉树本身就具有递归的性质,所以按照根->左子树->右子树的顺序遍历整个树。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
 int TreeSize(struct TreeNode* root)
 {
     return root==NULL?0:TreeSize(root->left)+TreeSize(root->right)+1;
 }
void preorder(struct TreeNode* root,int* a,int* pi)
{
    if(root==NULL)
        return;
    a[(*pi)++]=root->val;
    preorder(root->left, a, pi);
    preorder(root->right, a, pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
    *returnSize=TreeSize(root);
    int* a=(int*)malloc(*returnSize * sizeof(int));
    int i = 0;
    preorder(root, a, &i);
    return a;
}

3.png

4.png

目录
相关文章
|
10天前
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
18 0
|
13天前
|
存储 Java
JAVA数据结构刷题 -- 力扣二叉树
JAVA数据结构刷题 -- 力扣二叉树
19 0
|
14天前
[LeetCode]—— 226——翻转二叉树
[LeetCode]—— 226——翻转二叉树
|
14天前
[LeetCode]——965——单值二叉树
[LeetCode]——965——单值二叉树
|
14天前
LeetCode——101——对称二叉树
LeetCode——101——对称二叉树
39 12
|
14天前
|
存储
LeetCode———144—— 二叉树的前序遍历
LeetCode———144—— 二叉树的前序遍历
|
14天前
LeetCode——965. 单值二叉树
LeetCode——965. 单值二叉树
|
16天前
|
算法
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)(下)
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)
8 1
|
16天前
|
算法 C++
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)(上)
数据结构与算法⑮(第四章_下)二叉树OJ(力扣:144,965,104,110,226,100,101,572)
8 1
|
10天前
|
索引
【力扣刷题】两数求和、移动零、相交链表、反转链表
【力扣刷题】两数求和、移动零、相交链表、反转链表
18 2
【力扣刷题】两数求和、移动零、相交链表、反转链表