出自LeetCode #104 和 #662
今晚做1 (个整理)
/**
1. Definition for a binary tree node.
2. public class TreeNode {
3. int val;
4. TreeNode left;
5. TreeNode right;
6. TreeNode(int x) { val = x; }
7. }
104 二叉树的最大深度
class Solution{
int ans = 0;
public int maxDepth(TreeNode root) {
if(root == null) return 0;
maxDepth(root, 1);
return ans;
}
void maxDepth(TreeNode node, int depth);{
if(root == null) return;
if(node.left == null && node.right == null){
ans = Math.max(ans, depth);
}
maxDepth(node.left, depth + 1);
maxDepth(node.right, depth + 1);
}
}
662.二叉树最大宽度
从图中可以看出,设当前节点的坐标index。该节点的左节点为2 * index + 1, 右节点为2 * index + 2.
class Solution{
int max = 0;
HashMap <Integer,Integer> farLeft = new HashMap <Integer,Integer> ();
//用一个Map来记录当。前。层。第。一。个。index
public int widthOfBinaryTree(TreeNode root) {
dfs(root, 0, 0);
return max;
}
void dfs(TreeNode node, int depth, int index){
if(node == null) return;
if(!farLeft.containsKey(depth)){ //(important)记录当前层第一个index
farLeft.put(depth, index);
}
max = Math.max(max, index - farLeft.get(depth) + 1);
//记录该node的当前index和当前层的第一个index的差,保存最大的
dfs(node.left, depth + 1, index * 2 + 1);
dfs(node.right, depth + 1, index * 2 + 2);
}
}