亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網(wǎng)為廣大站長提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請做好本站友鏈:【 網(wǎng)站目錄:http://www.430618.com 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

本文介紹了查找二叉樹中大于x的節(jié)點(diǎn)數(shù)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

public static int nodesGreaterThanX(BinaryTreeNode<Integer> root,int k,int count)
{
    if(root==null)
        return 0;
    if(root.data>k){
        System.out.print(root.data + " ");
        count++;
    }
    int countLeft = nodesGreaterThanX(root.left, k,count);
    int countRight = nodesGreaterThanX(root.right, k,count);

    return count + countLeft + countRight;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    BinaryTreeNode<Integer> root = takeInput();
    int count = nodesGreaterThanX(root, 2,0);
    System.out.println();
    System.out.println(count);
}

我希望獲得大于x的節(jié)點(diǎn)數(shù)(在本例中為2),但我的答案不正確,并且我無法在程序中找到問題
如果不需要,請不要更改邏輯,并告訴我哪里出錯了。

推薦答案

如果您從根向下遍歷樹,則根本不需要向下傳播‘count’–這樣做會導(dǎo)致對節(jié)點(diǎn)的重復(fù)計(jì)數(shù),因?yàn)樗鼈儗?code>count、countLeftcountRight都有貢獻(xiàn),因?yàn)槟趯?code>count傳遞給nodesGreaterThanX之前對count遞增。

public static int nodesGreaterThanX(BinaryTreeNode<Integer> node, int k) {
  if (node == null) {
    return 0;
  }

  int countLeft = nodesGreaterThanX(node.left, k);
  int countRight = nodesGreaterThanX(node.right, k);

  return (node.data > k ? 1 : 0) + countLeft + countRight;
}

這篇關(guān)于查找二叉樹中大于x的節(jié)點(diǎn)數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,

分享到:
標(biāo)簽:二叉樹 大于 查找 節(jié)點(diǎn)
用戶無頭像

網(wǎng)友整理

注冊時間:

網(wǎng)站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運(yùn)動步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績評定2018-06-03

通用課目體育訓(xùn)練成績評定