获取Java中的二叉树中的节点级别
时间:2020-02-23 14:34:14 来源:igfitidea点击:
我们将在二叉树中搜索一个密钥。
root将在1级。
如果我们在二叉树中找到密钥,那么它的级别将为0。
算法 :
在二进制树中获取节点级别的步骤:
- 如果节点为null,则返回0
- 如果节点的数据等于键,则返回级别。
- 在左子树中递归搜索键
- 如果没有找到,则在右子树中搜索
递归的代码将是:
//Recursive Solution //To get level of node in a binary tree public static int getLevelOfNode(TreeNode root,int key,int level) { if(root==null) return 0; if(root.data==key) return level; int result=getLevelOfNode(root.left,key,level+1) ; if(result!=0) { //If found in left subtree , return return result; } result= getLevelOfNode(root.right,key,level+1); return result; }
允许创建Java程序以在二进制树中获取节点级别:
让我们说,你的二叉树是这样的:
package org.igi.theitroad.binarytree; public class BinaryTreeGetLevelNode { public static class TreeNode { int data; TreeNode left; TreeNode right; TreeNode(int data) { this.data=data; } } //Recursive Solution //To get level of node in a binary tree public static int getLevelOfNode(TreeNode root,int key,int level) { if(root==null) return 0; if(root.data==key) return level; int result=getLevelOfNode(root.left,key,level+1) ; if(result!=0) { //If found in left subtree , return return result; } result= getLevelOfNode(root.right,key,level+1); return result; } public static void main(String[] args) { //Creating a binary tree TreeNode rootNode=createBinaryTree(); System.out.println("Node data: 70,Level :"+getLevelOfNode(rootNode, 70, 1)); System.out.println("Node data: 100,Level :"+getLevelOfNode(rootNode, 100, 1)); System.out.println("Node data: 60,Level :"+getLevelOfNode(rootNode, 60, 1)); System.out.println("Node data: 40,Level :"+getLevelOfNode(rootNode, 40, 1)); } public static TreeNode createBinaryTree() { TreeNode rootNode =new TreeNode(40); TreeNode node20=new TreeNode(20); TreeNode node10=new TreeNode(10); TreeNode node30=new TreeNode(30); TreeNode node60=new TreeNode(60); TreeNode node50=new TreeNode(50); TreeNode node70=new TreeNode(70); rootNode.left=node20; rootNode.right=node60; node20.left=node10; node20.right=node30; node60.left=node50; node60.right=node70; return rootNode; } }
运行上面的程序,我们将获取以下输出:
Node data: 70,Level :3 Node data: 100,Level :0 Node data: 60,Level :2 Node data: 40,Level :1