本文介紹了查找二叉樹中大于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、countLeft和countRight都有貢獻(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ù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,






