亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算二叉樹中出現的次數

計算二叉樹中出現的次數

慕俠2389804 2023-01-05 16:52:23
假設一棵二叉樹可以有多個具有相同鍵的節點。計算其鍵等于值 v 的節點數。(它不是二叉搜索樹)。int countVal(int v):返回節點數 n where n.key = v結構:public class Tree {    Node root;    public Tree(Node root)         this.root = root;    }    public static class Node {        int key;        Node left;        Node right;        public Node(int key, Node left, Node right) {            this.key = key;            this.left = left;            this.right = right;        }    }}當然解決方法是使用遞歸,但我找不到正確的方法。
查看完整描述

1 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

這是問題的解決方案:


public int countVal(int v) {

    if(root == null)

        return -1;

    else

        return countValRec(v, root);

}


private int countValRec(int v, Node node) {

    if(node == null)

        return 0;

    else if(node.key == v)

        return nodeCountValRec(v, node.left) + 1 + nodeCountValRec(v, node.right);

    else

        return nodeCountValRec(v, node.left) + nodeCountValRec(v, node.right);

}


查看完整回答
反對 回復 2023-01-05
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號