Advertisement
LeatherDeer

Untitled

Nov 29th, 2022
654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. public static boolean isSameTree(TreeNode p, TreeNode q) {
  2.         if (p == null && q == null) {
  3.             return true;
  4.         }
  5.  
  6.         if (p == null || q == null) {
  7.             return false;
  8.         }
  9.  
  10.         return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
  11. }
  12.  
  13.     public static void dfs(TreeNode root, List<String> ans, String path) {
  14.         if (root == null) {
  15.             return;
  16.         }
  17.         // здесь мы точно не null, обновляем путь
  18.         path += root.val;
  19.  
  20.         if (root.left == null && root.right == null) {
  21.             ans.add(path);
  22.             return; // мы в листе, дальше смысла спускаться нет
  23.         }
  24.  
  25.         dfs(root.left, ans, path + "->");
  26.         dfs(root.right, ans, path + "->");
  27.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement