根据子节点数确定二叉树中的节点数

问题描述 投票:0回答:1

问题1:

二叉树的根节点T作为输入给出。我们必须找出T中的三种类型的节点之间的计数:具有0个子节点(即,叶子)的节点,具有1个子节点的节点和具有两个子节点的节点。

输出应该是一个数组,其中包含上述所有类型的节点的数量。

尽快帮助!

binary-tree nodes
1个回答
0
投票

我正在编写粗糙的代码,请检查它是否可以解决您的问题:

    HashMap<Integer, Integer> count = new HashMap<>();
    //For now, 0 key having a count of leaf nodes, 1 key count of nodes having a single child, 2 for both 

//使用顺序,前或后遍历树...使用countNodes获取计数

   public void inorder(TreeNode root){
       if(root == null) return;
       inorder(root.left);
       countNodes(root);
      inorder(root.right);
    }

  public void countNodes(TreeNode root){
       if(root == null) return;
       else if(root.left != null && root.right != null){
         count.put(2, 1 + count.getOrDefault(2,0));
       } 
      else if(root.left == null && root.right == null){
         count.put(0, 1 + count.getOrDefault(0,0));
       } 
      else{
         count.put(1, 1 + count.getOrDefault(1,0));
      } 
    }
© www.soinside.com 2019 - 2024. All rights reserved.