将二叉树存储到数组中 [英] Storing Binary Tree into an array

查看:91
本文介绍了将二叉树存储到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码将二叉树存储到数组中:

I attempting to store a binary tree into an array with the code below:

public void inorderArray(int[] array)  {
       inorderArray(root, array, 0);
}

private static Integer inorderArray(TreeNode root, int[] array, int index) { 
    // an inorder traversal that stores the items in array
    if(root == null){return index;}

    inorderArray(root.left, array, index);
    array[index++] = root.key;
    inorderArray(root.right, array, index);

    return index;
}

我不断得到 [94,95,0,0,0,0,0,0,0,0] ,而且也不是秩序井然.

I keep getting [94, 95, 0, 0, 0, 0, 0, 0, 0, 0], and its not in order either.

我不知道我在做什么错.感谢您的帮助.

I have no idea what I am doing wrong. Any help is appreciated.

推荐答案

您没有使用返回值.而且您需要使用它,因为在 index ++ 中进行的修改永远不会超出函数的范围.

You are not using the return value. And you need to use it, because the modification in index++ would never leave the scope of the function.

private static int inorderArray(TreeNode root, int[] array, int index) {
    if (root == null) {
        return index;
    }

    index = inorderArray(root.left, array, index);
    array[index++] = root.key;
    index = inorderArray(root.right, array, index);
    return index;
}

这篇关于将二叉树存储到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆