二叉树遍历

408第二轮复习到树实现一下通过递归遍

本题可以直接把数组开成固定值,不过就当练习一下统计节点数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
 * 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 countNode(struct TreeNode* root)
 {
    if(root == NULL){
        return 0;
    }else {
        return 1 + countNode(root->left) + countNode(root->right);
    }
 }
 //前序遍历
 void preorder(struct TreeNode* root,int* res,int* index)
 {
    if(root == NULL)return;
    res[*index] = root->val;
    (*index)++;
    preorder(root->left,res,index);
    preorder(root->right,res,index);

 }
 //中序遍历
 void inorder(struct TreeNode* root,int* res,int* index)
{
    if(root== NULL)return;

    inorder(root->left,res,index);
    res[*index] = root->val;
    (*index)++;
    inorder(root->right,res,index);

 }
  //后序遍历
 void postorder(struct TreeNode* root,int* res,int* index)
{
    if(root== NULL)return;

    postorder(root->left,res,index);
    postorder(root->right,res,index);
    res[*index] = root->val;
    (*index)++;
 }
int* Traversal(struct TreeNode* root, int* returnSize) 
{
    //求出返回数组的大小
    *returnSize = countNode(root);
    //用malloc开辟已求出的数组大小
    int* res = (int*)malloc(sizeof(int) * (*returnSize));
    //数组索引初始化
    int index = 0;
    preorder(root,res,&index);
    //inorder(root,res,&index);
    //postorder(root,res,&index);
    return res;

}

相关内容