day24--二叉树的建立

在BinaryCharTree类中新加入构造方法,使用一个线性表先分配所有节点的空间, 再将节点链接起来, 最后并没有返回, 而是把第 0 个节点的相应值拷贝给自己.
代码:

 public BinaryCharTree(char[] paraDataArray, int[] paraIndicesArray) {
        // Step 1. Use a sequential list to store all nodes.
        int tempNumNodes = paraDataArray.length;
        BinaryCharTree[] tempAllNodes = new BinaryCharTree[tempNumNodes];
        for (int i = 0; i < tempNumNodes; i++) {
            tempAllNodes[i] = new BinaryCharTree(paraDataArray[i]);
        }// of if
        // Step 2. Link these nodes.
        for (int i = 1; i < tempNumNodes; i++) {
            for (int j=0; j < i; j++) {
                System.out.println("indices " + paraIndicesArray[j] + " vs. " + paraIndicesArray[i]);
                if (paraIndicesArray[i] == paraIndicesArray[j] * 2 + 1) {
                    tempAllNodes[j].leftChild = tempAllNodes[i];
                    System.out.println("Linking " + j + " with " + i);
                    break;
                } else if (paraIndicesArray[i] == paraIndicesArray[j] * 2 + 2) {
                    tempAllNodes[j].rightChild = tempAllNodes[i];
                    System.out.println("Linking " + j + " with " + i);
                    break;
                } // Of if
            }// of for j
        }// of for i
        //Step 3. The root is the first node.
        value = tempAllNodes[0].value;
        leftChild = tempAllNodes[0].leftChild;
        rightChild = tempAllNodes[0].rightChild;
    }// of the constructor

运行结果:

indices 0 vs. 1
Linking 0 with 1
indices 0 vs. 2
Linking 0 with 2
indices 0 vs. 4
indices 1 vs. 4
Linking 1 with 3
indices 0 vs. 5
indices 1 vs. 5
indices 2 vs. 5
Linking 2 with 4
indices 0 vs. 12
indices 1 vs. 12
indices 2 vs. 12
indices 4 vs. 12
indices 5 vs. 12
Linking 4 with 5

Preorder visit: 
A
B
D
C
E
F

In-order visit: 
B
D
A
E
F
C

Post-order visit: 
D
B
F
E
C
A

Process finished with exit code 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值