Advertisement
FNSY

863. All Nodes Distance K in Binary Tree

Jun 8th, 2022
1,256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. class Solution {
  11.     List<Integer> list = new ArrayList<>();
  12.     int val;
  13.     private void searchSubTree(TreeNode root, int count, int k) {
  14.         if (root == null) return;
  15.         if (count == k) {
  16.             list.add(root.val);
  17.             return;
  18.         }
  19.         searchSubTree(root.left, count + 1, k);
  20.         searchSubTree(root.right, count + 1, k);
  21.     }
  22.    
  23.     private int trav(TreeNode root, TreeNode target, int k, int count) {
  24.         if (root == null) return 0;
  25.         if (root == target) {
  26.             searchSubTree(target, 0, k);
  27.             return 1;
  28.         }
  29.  
  30.         int newCount = count + 1;
  31.        
  32.         int left = trav(root.left, target, k, count > 0 ? newCount : count);        
  33.         int right = trav(root.right, target, k, left > 0 ? newCount : count);
  34.         if (left > 0) searchSubTree(root.right, left + 1, k);
  35.         else if (right > 0) searchSubTree(root.left, right + 1, k);
  36.        
  37.         if ((left == k || right == k) && k > 0) list.add(root.val);
  38.         return left > 0 ? left + 1 : right > 0 ? right + 1 : 0;
  39.     }
  40.     public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
  41.         trav(root, target, k, 0);
  42.         return list;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement