zoukankan      html  css  js  c++  java
  • Get Level of a node in a Binary Tree

    Given a Binary Tree and a key, write a function that returns level of the key.

    For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function should return 0.

    思路:DFS,递归来做。 或者BFS都行吧。来个递归先

     1 public class DepthOfRandomNode {
     2     public int getDepth(TreeNode root, TreeNode target) {
     3         return helper(root, target, 0);
     4     }
     5     private static int helper(TreeNode root, TreeNode target, int level) {
     6         if (root == null) {
     7             return 0;
     8         }
     9         if (root.val == target.val) {
    10             return level + 1;
    11         }
    12         int left = helper(root.left, target, level + 1);
    13         int right = helper(root.right, target, level + 1);
    14         if (left != 0) {
    15             return left;
    16         }else if(right != 0) {
    17             return right;
    18         }else{
    19             return 0;
    20         }
    21     }
    22     public static void main(String[] args) {
    23         TreeNode root = new TreeNode(1);
    24         TreeNode left1 = new TreeNode(2);
    25         TreeNode right1 = new TreeNode(3);
    26         TreeNode left21 = new TreeNode(4);
    27         TreeNode left22 = new TreeNode(5);
    28         TreeNode right21 = new TreeNode(6);
    29         TreeNode right22 = new TreeNode(7);
    30         root.left = left1;
    31         root.right = right1;
    32         left1.left = left21;
    33         left1.right = right21;
    34         right1.left = left22;
    35         right1.right = right22;
    36         DepthOfRandomNode test = new DepthOfRandomNode();
    37         System.out.println(test.getDepth(root,root));
    38     }
    39 }
  • 相关阅读:
    记住我
    国米夺冠
    小谈“汉字转换成拼音(不带声调)”
    NLP资源共享盛宴
    文本分类资源和程序开源共享
    菜鸟进阶:C++实现Chisquare 特征词选择算法
    欢迎大家试用信息领域学科知识服务平台
    欢迎大家加入NLP,WEBIR,DATA Ming 的技术QQ群
    求两点之间所有路径的算法
    step by step 文本分类(一)
  • 原文地址:https://www.cnblogs.com/gonuts/p/4650925.html
Copyright © 2011-2022 走看看