验证给定级别的所有节点在二叉树中具有不同的值

时间:2018-02-14 18:44:14

标签: java algorithm recursion binary-tree

我的问题是,这个问题可以解决没有使用任何数据结构(堆栈,列表等),还是需要一个? (如果可能的话,我也希望看到两种情况下的解决方案。)

问题:

有一个BinaryTree类,表示包含整数值的二叉树。假设已经实现了方法:

const PREVENT_DIRECT_IMPORT: InjectionToken<boolean> = new InjectionToken('FeatureModule:PREVENT_DIRECT_IMPORT');

@NgModule({
  declarations: FEATURE_COMPONENTS,
  entryComponents: FEATURE_COMPONENTS,
  imports: [ ... ],
  exports: [ ... ]
  providers: [{
    // erroneous provider when module is directly imported
    provide: PREVENT_DIRECT_IMPORT,
    useFactory: () => { throw new Error('Correct usage info'); },
    multi: false
  }]
})
export class FeatureModule {
  public static setParentState(stateName: string): ModuleWithProviders {
    ...
    return {
      ngModule: FeatureModule,
      providers: [
        ...UIRouterModule.forChild({ states: ... }).providers
        // my providers
        {
          provide: FEATURE_PROVIDER_TOKEN,
          useValue: ...
          multi: false
        }, {
          // this is the same provider when module is correctly imported
          provide: PREVENT_DIRECT_IMPORT,
          useValue: true,
          multi: false
        }
      ]
    };
  }

  constructor(
    @Import(PREVENT_DIRECT_IMPORT) prevent: boolean
  ) {
    // direct import will throw error when DI tries to get the injected provider
  }
}

实施以下递归方法:

public BinaryTree right();  // returns right children
public BinaryTree left();   // returns left children
public int val();   // returns value of root node.
只有当 a 级别 lev 的节点的所有值都有不同时,

接收整数二进制树并返回 true 值。

提前感谢您的时间。

3 个答案:

答案 0 :(得分:2)

我们可以使用HashSet<Integer>来跟踪lev级别的数据。

public static boolean allDifferentAtLevel(BinaryTree a, int lev){
    return checker(new HashSet<Integer>(),a,0,lev); //EmptySet, Root, CurrentLevel, Level
}

public static boolean checker(HashSet<Integer> set,BinaryTree a, int currentLevel, int lev) {
    if(a==null) //If current node of tree is null, return true.
        return true;

    if(currentLevel==lev) //If currentLevel is the required level, We don't need to move further.
                          //We can just validate the data at currentLevel and return the appropriate value.
    {
        int value=a.val();
        if(set.contains(value)) //If set contains the value, Duplication found.
            return false;

        set.add(value);
        return true;
    }

    //Check for both of the children.
    return checker(set,a.left(),currentLevel+1,lev) && checker(set,a.right(),currentLevel+1,lev);
}

答案 1 :(得分:1)

但是它可能会效率低下 - 你可以实现两个递归函数:

  1. 使DFS以所需级别到达所有节点
  2. 从第一个函数(对于所需级别的每个节点)调用另一个函数,该函数计算(也使用DFS)所有节点的值等于第一个函数考虑的节点的值,并检查这个count等于1.

答案 2 :(得分:0)

是的,这可以通过递归来解决,而无需额外的数据结构。

让我们尝试定义不同allDifferentAtLevel(BinaryTree tree, int lev)的{​​{1}}方法应该是什么样的:

对于lev,结果只是lev=0,因为级别false上的所有节点都具有相同的值。在级别0上只有一个节点,因此所有节点具有相同的值。

对于0,检查lev=1(添加tree.right().val() == tree.left().val()支票)非常简单。

对于更高级别(null),您应该递归调用该方法。基本上,lev>1allDifferentAtLevel(tree.left(), lev - 1)会确保左子树和右子树满足条件。不幸的是,这是不够的,因为左右子树可能在它们之间有一些共同的价值。

但是可以解决这个检查,不仅仅是左右,而且所有子树的组合都更深层次。类似的东西:

allDifferentAtLevel(tree.right(), lev - 1)

有两个更深层次的子树(BinaryTree ll = tree.left() == null ? null : tree.left().left(); BinaryTree lr = tree.left() == null ? null : tree.left().right(); BinaryTree rl = tree.right() == null ? null : tree.right().left(); BinaryTree rr = tree.right() == null ? null : tree.right().right(); BinaryTree ll_lr = tree.left(); BinaryTree ll_rl = new BinaryTree(0, ll, rl); BinaryTree ll_rr = new BinaryTree(0, ll, rr); BinaryTree lr_rl = new BinaryTree(0, lr, rl); BinaryTree lr_rr = new BinaryTree(0, lr, rr); BinaryTree rl_rr = tree.right(); return allDifferentAtLevel(ll_lr, lev - 1) && allDifferentAtLevel(ll_rl, lev - 1) && allDifferentAtLevel(ll_rr, lev - 1) && allDifferentAtLevel(lr_rl, lev - 1) && allDifferentAtLevel(lr_rr, lev - 1) && allDifferentAtLevel(rl_rr, lev - 1); lllrrl)。但是我们不能只检查这些子树,我们必须互相检查它们。这些子树有六种可能的不同对。为了相互检查这些子树,我们可以为每个不同的对创建一个二叉树(rrll_lrll_rlll_rr,{{1 },lr_rl)然后递归地检查每个二叉树。如果lr_rrrl_rrlllr中的任何子树在rl上具有相同的元素,则会有一对具有相同元素的子树rr

所以是的,这个问题可以通过递归来解决,而无需额外的数据结构。我不会在这里考虑lev-2其他数据结构。

话虽如此,使用像集合这样的附加数据结构可以使任务更容易。

相关问题