题目:node
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.函数
Example:
Given a binary tree spa
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].递归
Note: The length of path between two nodes is represented by the number of edges between them.get
解决:hash
① 题目要求求出二叉树的直径:二叉树中从一个结点到另外一个节点最长的路径,叫作二叉树的直径it
咱们能够理解为求根节点的左右子树的深度和,那么咱们只要对每个结点求出其左右子树深度之和,就能够更新结果diameter了。为了减小重复计算,咱们用hashmap创建每一个结点和其深度之间的映射,这样某个结点的深度以前计算过了,就不用再次计算了。io
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/class
public class Solution {//321 ms
public int diameterOfBinaryTree(TreeNode root) {
if(root == null) return 0;
int diameter = getDepth(root.left) + getDepth(root.right);
return Math.max(diameter,
Math.max(diameterOfBinaryTree(root.left),diameterOfBinaryTree(root.right)));//不仅是头节点
}
public int getDepth(TreeNode node){
Map<TreeNode,Integer> map = new HashMap<>();
if(node == null) return 0;
if(map.containsKey(node) && map.get(node) > 0) return map.get(node);
int depth = Math.max(getDepth(node.left),getDepth(node.right)) + 1;
map.put(node,depth);
return map.get(node);
}
}hashmap
② 思路和上一个相同,可是要简洁的多,没有使用map,只使用一个递归便可。在求深度的递归函数中顺便就把直径算出来了。
public class Solution {//10ms
int diameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
getDepth(root);
return diameter;
}
private int getDepth(TreeNode root) {
if(root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
diameter = Math.max(diameter, left + right); //不是left + right + 1。。是path。。不是number of node
return Math.max(left, right) + 1;
}
}
③ 进化版。
public class Solution {//9ms
int depth = 0;
public int diameterOfBinaryTree(TreeNode root) {
getDepth(root);
return depth;
}
public int getDepth(TreeNode root) {
if (root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
if (depth < left + right) {
depth = left + right;
}
return left > right ? left + 1 : right + 1;
}
}
④ 比较好理解的
class Solution {//23ms public int diameterOfBinaryTree(TreeNode root) { if(root == null) return 0; int diameter = getDepth(root.left) + getDepth(root.right); return Math.max(diameter,Math.max(diameterOfBinaryTree(root.left),diameterOfBinaryTree(root.right))); } public int getDepth(TreeNode root){ if(root == null) return 0; return Math.max(getDepth(root.left),getDepth(root.right)) + 1; } }