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;
    }
}

 

posted on 2022-05-05 11:03  一仟零一夜丶  阅读(36)  评论(0)    收藏  举报