简体   繁体   English

创建二叉树的时间复杂度

[英]time complexity of creating of binary tree

There is a method that builds a binary tree in which there are N full levels and on each level I there are two nodes whose information parts are equal to I. What is the time complexity depending on the number of levels of the tree built?有一种构建二叉树的方法,其中有 N 个完整级别,在每个级别 I 上有两个节点,其信息部分等于 I。根据构建树的级别数,时间复杂度是多少?

private SimpleTreeNode fromNDigitToNode(int x,int k) throws Exception {
        IndexWrapper iw = new IndexWrapper();
        T parentValue = readValue((k-x+1)+"",iw);
        SimpleTreeNode parentNode = new SimpleTreeNode(parentValue);
        SimpleTreeNode leftNode = new SimpleTreeNode(parentValue);
        SimpleTreeNode rightNode = new SimpleTreeNode(parentValue);
        if(x<=1)return parentNode;
        int z = --x;
            parentNode.left = fromNDigitToNode(z,k);
            parentNode.right = fromNDigitToNode(z,k);

        return parentNode;
    }
public void fromNDigit(String Ndigit) throws Exception{
        int digit = Integer.parseInt(Ndigit);

        IndexWrapper iw = new IndexWrapper();
        SimpleTreeNode root = fromNDigitToNode(digit,digit);

        this.root = root;
    }
}

I think your code is flawed.我认为你的代码有缺陷。 You create leftNode and rightNode, but you don't use them.您创建了 leftNode 和 rightNode,但不使用它们。 Furthermore, both parentNode.left and parentNode.right are created with the same parameters.此外,parentNode.left 和 parentNode.right 都是使用相同的参数创建的。 Is that correct?那是对的吗?

I have no idea what your IndexWrapper is for and what readValue() does.我不知道您的 IndexWrapper 是做什么用的以及 readValue() 的作用。

And the biggest problem: this never stops.最大的问题是:这永远不会停止。 You don't check (for instance) if x < 0. So you call it with x=1.你不检查(例如)如果 x < 0。所以你用 x=1 来调用它。 You then recurse twice, calling it with x=0, then x=-1, and repeat forever.然后你递归两次,用 x=0 调用它,然后 x=-1,并永远重复。

So I'd say this is Order(forever).所以我会说这是 Order(forever)。

Might I suggest you actually get your code to work, test it, and THEN figure out the complexity.我可能会建议您实际让您的代码运行、测试它,然后找出复杂性。

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

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