題目: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; } }