繁体   English   中英

二叉树中的有序遍历

[英]In-order traverse in a binary tree

我试图编写一个函数以按顺序遍历二叉树并将其项按顺序放入整数数组。我知道这段代码包含一些不好的做法,但我想知道实际上是为什么我的函数没有创建目标整数数组,例如即使我的函数可以找到保留bst所有项目所需的大小,也无法正确放置这些项目,有时仅放置2个节点,有时仅放置根。

我看不到任何将任何主要功能放在这里的原因,因为我只会将其用于打印该数组的元素。

我的函数,一个TreeNode的全局变量和typedef块;

typedef struct TreeNode{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
} TreeNode;

    int ctr = 0;
    int size = 0;

    int* inorder(TreeNode *root, int* arr){

        if(ctr==0) /*if first call to this function*/
            arr = malloc(size*sizeof(int)) ;

        ctr++ ; 

        if(root){

            if(!root->left && !root->right){        
                arr = realloc(arr, ++size*sizeof(int)) ;
                arr[size-1] = root->val ;
            }

            else if(!root->left&&root->right){
                arr = realloc(arr, ++size*sizeof(int)) ;
                arr[size-1] = root->val ;
                arr=inorder(root->right,arr) ;  
            }
            else if(!root->right&&root->left){
                arr=inorder(root->left,arr) ;
                arr = realloc(arr, ++size*sizeof(int)) ;
                arr[size-1] = root->val ;
            }
            else{
                arr=inorder(root->left,arr) ;
                arr = realloc(arr, ++size*sizeof(int)) ;
                arr[size-1] = root->val ;
                arr=inorder(root->right,arr) ;

            }

            return arr ;
        }
        else
            return arr ;
    }

哎呀,您在每个函数调用处都在执行realloc()。 realloc()成本很高,应尽可能少地使用。 您应该将树的大小保持在某个地方。 如果不能,则可以第一次遍历它以计算元素的数量。

另一件事:您的if / elseif / elseif / else没用:您可以始终应用相同的处理方法。 伪代码,假设对于任何节点left->val < node->val < right->val

  1. 获取树的大小(如果还没有的话)
  2. malloc()一个大小为size * sizeof(int)的数组(这是您唯一需要的分配),将索引初始化为0

然后,您可以进行简单的递归:

void inorder(Treenode *root, int *array, int *index) {
    if (!root)
        return;

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

就是这样!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM