687 Longest Univalue Path
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans = 0;
public int longestUnivaluePath(TreeNode root) {
if (root == null) return 0;
dfs(root);
return ans;
}
private int dfs(TreeNode root){
if (root == null) return 0;
int leftAns = dfs(root.left);
int rightAns = dfs(root.right);
int goLeft = 0, goRight = 0;
if (root.left != null && root.left.val == root.val) goLeft += leftAns + 1;
if (root.right != null && root.right.val == root.val) goRight += rightAns + 1;
ans = Math.max(ans, goLeft + goRight);
//System.out.println("Node: " + root.val + " ans: " + ans + " left: " + goLeft + " right: " + goRight);
return Math.max(goLeft, goRight);
}
}
652 Find Duplicate Subtrees
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<TreeNode> ans;
Map<String, Integer> hash;
public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
hash = new HashMap<>();
ans = new ArrayList<>();
dfs(root);
return ans;
}
private String dfs(TreeNode root){
if (root == null) return "#";
String cur = root.val + "," + dfs(root.left) + "," + dfs(root.right);
if (!hash.containsKey(cur)){
hash.put(cur, 1);
}
else{
hash.put(cur, hash.get(cur) + 1);
}
if (hash.get(cur) == 2) ans.add(root);
return cur;
}
}
504 Base 7
class Solution {
public String convertToBase7(int num) {
if (num < 0) return "-" + convertToBase7(-num);
if (num < 7) return num + "";
return convertToBase7(num / 7) + num % 7;
}
}