1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class FindElements { Set<Integer> set = new HashSet<>(); public FindElements(TreeNode root) { dfs(root, null, 0); }
public void dfs(TreeNode root, Integer rootValue, int flag) { if (root == null) { return; }
if (rootValue == null) { root.val = 0; }else { if (flag == 0) { root.val = 2*rootValue + 1; }else { root.val = 2*rootValue + 2; } } set.add(root.val);
if (root.left != null) { dfs(root.left, root.val, 0); }
if (root.right != null){ dfs(root.right, root.val, 1); } } public boolean find(int target) { if (set.contains(target)) { return true; } return false; } }
|