【问题标题】:Construction of binary tree by applying functions on parent通过在父节点上应用函数构建二叉树
【发布时间】:2018-10-12 13:17:56
【问题描述】:

我有一个给定的数字“X”。 我有两个函数 f(x) 和 g(x)。现在我想构造一棵二叉树,其中 X 作为父节点,f(X) 作为左子节点,g(X) 作为右子节点,并在所有子节点上继续这个过程,如果我找到一个相等的元素则终止到两个子子树中的 X。 我该如何实现?

【问题讨论】:

  • 您使用什么语言?您正在构建的二叉树的定义是什么? fg的类型是什么?
  • 我正在使用 python。 f(X)=X+c 其中 c 是常数,g(X) 是 X 的位数之和
  • 另外,我不想构建 BST

标签: python tree binary-tree


【解决方案1】:

你可以尝试用这种方式来做(这只是一个伪代码,不是字面语法):

public boolean myFunc(int x){
    // BFS on left subtree ///////////////////////////////////
    boolean ltreeContainsX = false;
    int dx = f(x); // f should be defined somewhere
    if(dx == x){
        ltreeContainsX = true;
    }else{
        ArrayDeque<Integer> q = new ArrayDeque<Integer>();
    q.push(dx);
    while(q.size()!=0){
        int val = q.pop();
        int fval = f(val);
        q.push(fval);
        if(fval == x){
            lTreeContainsX = true;
            break;
        }
        int gval = g(val);
        q.push(gval);
        if(gval == x){
            lTreeContainsX = true;
            break;
        }
    }
    }
    // BFS on right subtree ///////////////////////////////////
    // ... do the same as the above code snippet, but this time,
    // you will push g(x) to an empty queue first and then proceed
    // find the boolean value called rtreeContainsX

    return ltreeContainsX && rtreeContainsX;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多