1.获取树中结点的数量
发布时间:2025-06-24 15:02:54 作者:北方职教升学中心 阅读量:562
方法2。
方法1。
// 检测值为value的元素是否存在, 。
public int leafNodecount2(TreeNode root){ if(root==null){ return 0; } if(root.right==null&&root.left==null){ return 1; } //叶数=右子树的叶数+左树的叶数 return leafNodecount2(root.left)+ leafNodecount2(root.right); }。方法2。1.获取树中结点的数量。public int size2(TreeNode root){ if(root==null){ return 0; } return size2(root.left)+size2(root.right)+1; }。
// 获取叶节点的数量 //叶子:度为0的节点 public static int leafSize=0; public void getLeafNodeCount(TreeNode root){ if(root==null){ return; } ///叶:0度c;没有左子树和右子树 if(root.right==null&&root.left==null){ leafSize++; } //叶数=右子树的叶数+左树的叶数 getLeafNodeCount(root.left); getLeafNodeCount(root.right); }。
个人主页:♡喜欢做梦。
方法2。1.获取树中结点的数量。public int size2(TreeNode root){ if(root==null){ return 0; } return size2(root.left)+size2(root.right)+1; }。
// 获取叶节点的数量 //叶子:度为0的节点 public static int leafSize=0; public void getLeafNodeCount(TreeNode root){ if(root==null){ return; } ///叶:0度c;没有左子树和右子树 if(root.right==null&&root.left==null){ leafSize++; } //叶数=右子树的叶数+左树的叶数 getLeafNodeCount(root.left); getLeafNodeCount(root.right); }。
个人主页:♡喜欢做梦。
3.获取第k层节点的数量。
4.获得二叉树的高度 。
。
5.判断元素的位置。在哪个节点 public TreeNode find(TreeNode root, char val){ if(root==null){ return null; } if(root.val==val){ return root; } TreeNode left=find(root.left,val); //如果目标是左子树,直接返回左节点 if(left!=null){ return left; } TreeNode right=find(root.right,val); //如果目标是右子树,直接返回右节点 if(right!=null){ return right; } //没有回到null return null; }。
// 获得二叉树的高度 ///看左子树和右子树的高度 ///取左子树和右子树的最大高度 public int getHeight(TreeNode root){ if(root==null){ return 0; } int leftheight=getHeight(root.left); int rightheight=getHeight(root.right); return Math.max(leftheight,rightheight)+1; }。
。
二叉树的基本遍历。
public static int nodeSize=0; // 获取树中节点的数量 public void size(TreeNode root){ //判断是否有节点 if(root==null){ return ; } nodeSize++; //左子树节点遍历 size(root.left); //遍历右子树节点 size(root.right); }。
2.获取节点数量 。



。今天写在这里,二叉树的基本操作包括层序遍历和判断完全二叉树,也许我以后会写的。
// 获得第K层节点的个数 public int getKLevelNodeCount(TreeNode root,int k){ if(root==null){ return 0; } //当k==1点,表示目前要找到的级别 if (k==1){ return 1; } ///递归左右子树直到k==1,到搜索的层次 ///左子树这个层次的节点数+右子树这个层次的节点数 return getKLevelNodeCount(root.left,k-1)+ getKLevelNodeCount(root.right,k-1); }。
。
。这篇文章可能不是很好,感谢您的支持🌹 🌹 🌹