LeetCode 543 Diameter of Binary Tree

来源:互联网 发布:淘宝贷款15万交3000 编辑:程序博客网 时间:2024/06/08 06:00

题目:

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 

          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.

题目链接

题意:

给一棵二叉树,要求寻找其中最长的路径,其中,路径的定义是任意两个节点之间的距离,,最长的路径也可能不经过根节点。

通过观察可以得出,对于一个父节点,两个子节点都存在的节点而言,经过它的路径有两个方向可以选择,假如从左子节点传入,可从右子节点传出寻找最大长度,也可能从父节点传出寻找最大长度,假如只有一个子节点,那就只能选一条路。利用遍历,从下层递归到上层,便可得到最大长度。

代码如下:

class Solution {public:    int ans = 0;    int dfs(TreeNode* node) {        if (!node) return 0;        int left = dfs(node->left);        int right = dfs(node->right);        ans = max(ans, left + right);        return 1 + max(left, right);    }    int diameterOfBinaryTree(TreeNode* root) {        dfs(root);        return ans;    }};