【问题标题】:counting the right nodes of a binary tree计算二叉树的右节点
【发布时间】:2023-03-25 15:15:01
【问题描述】:

我想统计一棵二叉树的正确节点,例如下面这个:

    15
   /
10
   \
    14

所以我做了以下程序:

public class NodeT {
    int elem;
    NodeT left;
    NodeT right;
    public NodeT(int elem){
        this.elem=elem;
        left=null;
        right=null;
    }
}


public class Tree {
    public NodeT createTree(){
        NodeT root=new NodeT(15);
        NodeT n1=new NodeT(10);
        NodeT n4=new NodeT(14);
        root.left=n1;
        n1.right=n4;
        return root;
    }
 public int countRight(NodeT root){
         if (root==null) return 0;    //version 1
         else{
             return 1+countRight(root.right);
         }
     }

我通过以下方式调用我的主程序:

Tree tree=new Tree();
NodeT root=tree.createTree();
System.out.println(tree.countRight(root))

此代码打印 1 作为正确答案,但我不明白为什么会发生这种情况。对于我看到的 15 的右分支等于 null,因此对递归函数 countRight() 的调用应该返回 0 并打印一个不正确的答案。

我见过其他解决方案,我发现为了计算所有节点,他们使用如下解决方案:

     static int n;
     public int countRight(NodeT root){   //version 2
         if (root==null) return 0;
         if (root.left!=null){
             n=countRight(root.left);
         }
         if (root.right!=null){
             n++;
             n=countRight(root.right);
         }
         return n;
     }

这对我来说似乎更合法。会不会是第一个版本失败的情况?

谢谢

【问题讨论】:

  • 你没有添加左子树的右节点
  • 那棵树你应该得到什么答案?
  • 您返回 1+countRight(root.right) 而不对 root.right 进行空检查。这意味着即使正确的节点为空,您仍要为其添加一个。此外,您永远不会像皇家幽灵所指出的那样检查树的左侧。为此,您还需要在退货中添加+countRight(root.left)

标签: java


【解决方案1】:

这样的方法不应该使用静态字段,或者任何字段。

任务是统计正确的节点数,其实就是统计right不为空的节点数。您实际上并不是在计算节点,而是对节点的引用。

这也意味着你必须扫描所有个节点,这意味着方法必须左右遍历。

最后,根节点根据定义不是正确的节点。

public int countRight(NodeT node) {
    if (node == null)
        return 0;
    if (node.right == null)
        return countRight(node.left);
    return 1 + countRight(node.left) + countRight(node.right);
}

【讨论】:

  • 谢谢@Andreas,你能给我一个版本1失败的例子吗?因为当我运行它时,它似乎打印了正确的答案
  • @Little 当然,将root.left=n1 更改为root.right=n1。这将使节点 15 成为根节点,节点 10 和 14 将成为右节点,因此 2 个右节点,但您的代码返回 3。--- 或者,将 n1.right=n4 更改为 n1.left=n4。这将使节点 10 和 14 成为左节点,因此 0 个右节点,但您的代码返回 1。
【解决方案2】:

您的第一个代码将返回 2 绝不会返回 1 递归调用

返回 1+另一个更深的调用,直到 root.right==null

将根据您的结构产生 2 个回报 您编码的树与您绘制的树不同

【讨论】:

  • “它不可能返回 1” 好吧,问题是 “这个代码打印 1”,所以它显然会发生,它确实是因为它计算根节点,仅此而已,因为 "another deep call until root.right==null" 立即为真(提示:root.right = null)。
  • 这将返回 2 它显然不是 1 go it 1 不等于 2 ok 并且 draw dosnt 代表代码它完全不同的结构你明白吗?
  • createTree() 方法创建了图中所示的树。有 3 个节点,值分别为 15、10 和 14,所以我们称它们为 n15、n10 和 n14。当您使用根 (n15) 调用 countRight() 的第一个版本时,它将执行 1 + countRight(n15.right)。由于n15.right 为null,所以调用do return 0,这意味着第一个调用最终是return 1 + 0,因此最终结果是1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 2012-10-04
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多