力扣--543.二叉树的直径-代码

/**

  • Definition for a binary tree node.
  • public class TreeNode {
  • int val;
    
  • TreeNode left;
    
  • TreeNode right;
    
  • TreeNode() {}
    
  • TreeNode(int val) { this.val = val; }
    
  • TreeNode(int val, TreeNode left, TreeNode right) {
    
  •     this.val = val;
    
  •     this.left = left;
    
  •     this.right = right;
    
  • }
    
  • }
    */
    class Solution {
    int res = 0;
    public int diameterOfBinaryTree(TreeNode root) {
    solve(root);
    return res;
    }

int solve(TreeNode root){
if(root == null){
return 0;
}
int left = solve(root.left);
int right = solve(root.right);
res = Math.max(left + right, res);
return Math.max(left, right) + 1;
}

}

时间:O(n)
空间:O(n)

上一篇:【C语言】bool 关键字详解


下一篇:STM32:实现ping命令(lwip)