Leetcode学习笔记:#543. Diameter of Binary Tree

匿名 (未验证) 提交于 2019-12-02 23:35:02

Leetcode学习笔记:#543. Diameter of Binary Tree

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.

实现:

int max = 0;          public int diameterOfBinaryTree(TreeNode root) {         maxDepth(root);         return max;     }          private int maxDepth(TreeNode root) {         if (root == null) return 0;                  int left = maxDepth(root.left);         int right = maxDepth(root.right);                  max = Math.max(max, left + right);                  return Math.max(left, right) + 1;     }

思路:
前序遍历二叉树,用max保存当前最大值并决定是否更新

文章来源: https://blog.csdn.net/ccystewart/article/details/90575624
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!