543. 二叉树的直径
package leetcode; public class demo_543 { int max=0; public int diameterOfBinaryTree(TreeNode root) { order(root); return max; } public void order(TreeNode root) { //max为所有节点深度的最大值 if(root!=null) { if(treeHeight(root.left)+treeHeight(root.right)>max) { max=treeHeight(root.left)+treeHeight(root.right); } order(root.left); order(root.right); } } //求出当前节点的深度 public int treeHeight(TreeNode root) { return root==null?0:Math.max(treeHeight(root.left), treeHeight(root.right))+1; } }
浙公网安备 33010602011771号