加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

计算二叉树中节点值小于某个数的节点个数

(2008-10-27 14:25:09)
标签:

二叉树

递归

数据结构

java

it

分类: Java

class Node  //节点,也可叫做树,可以添加左子树和右子树
{
 public static final int LEFT = 1;
 public static final int RIGHT = 2;
 private int value;
 private Node left=null;
 private Node right=null;
 Node(int value){
  this.value = value;
 }
 public void addSon(Node node,int sontype)throws Exception{
  if(sontype==Node.LEFT&&this.left==null){
   this.left=node;
  }else if(sontype==Node.RIGHT&&this.right==null){
   this.right = node;
  }else{
   throw new Exception("添加子节点出错!");
  }
 }
 public boolean hasLeft(){
  if(this.left==null){
   return false;
  }else{
   return true;
  }
 }
 public boolean hasRight(){
  if(this.right==null){
   return false;
  }else{
   return true;
  }
 }
 public boolean isLeaf(){
  if(this.left==null&&this.right==null){
   return true;
  }else{
   return false;
  }
 }
 public int getValue(){
  return this.value;
 }
 public Node getLeft() throws Exception{
  if(this.hasLeft()){
   return this.left;
  }else{
   throw new Exception("没有左子树");
  }
 }
 public Node getRight() throws Exception{
  if(this.hasRight()){
   return this.right;
  }else{
   throw new Exception("没有右子树");
  }
 }
}


public class Tree
{
 public int count=0;
 public static void main(String[] args) throws Exception
 {
   
     
     
  Node root = new Node(200);
  Node parent21= new Node(211);
  Node parent22 = new Node(300);
  Node parent31 = new Node(322);
  Node parent32 = new Node(322);
  Node parent33 = new Node(122);
  Node leaf1 = new Node(3883);
  Node leaf2 = new Node(333);
  Node leaf3 = new Node(88);
  Node leaf4 = new Node(800);
  Node leaf5 = new Node(883);
  Node leaf6 = new Node(933);
  parent31.addSon(leaf1,Node.LEFT);
  parent31.addSon(leaf2,Node.RIGHT);
  parent32.addSon(leaf3,Node.LEFT);
  parent32.addSon(leaf4,Node.RIGHT);
  parent33.addSon(leaf5,Node.LEFT);
  parent33.addSon(leaf6,Node.RIGHT);
  parent21.addSon(parent31,Node.LEFT);
  parent21.addSon(parent32,Node.RIGHT);
  parent22.addSon(parent33,Node.LEFT);
  root.addSon(parent21,Node.LEFT);
  root.addSon(parent22,Node.RIGHT);
  

  Tree tree = new Tree();
 // tree.counter(root,300);   //调用方法数小于300的节点个数
 // System.out.println(tree.count);
  System.out.println(tree.counter(root,300));

 }
 //递归数节点小于v的节点个数,找到一个count加1
 public int counter(Node node,int v)throws Exception{
  int count = 0;
  if(node.getValue()<v){  //如果当前节点值小于v,count变成1;
   count++;
  }
  if(node.isLeaf()){   //如果当前节点是页节点,则返回count
   return count;
  }
  if(node.hasLeft()){     //如果当前节点有左子树,则递归调用,数左子树中值小于v的节点个数
   count = count+counter(node.getLeft(),v);
  }
  if(node.hasRight()){    //如果当前节点有右子树,则递归调用,数右子树中值小于v的节点个数
   count =  count+counter(node.getRight(),v);
  }
  return count;
 }
}

0

阅读 收藏 喜欢 打印举报/Report
后一篇:java面试题
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有