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 }
时间: 2024-11-09 01:49:47