leetcode编程记录9 #543 Diameter of Binary Tree

来源:互联网 发布:福禄克网络测试仪使用 编辑:程序博客网 时间:2024/05/18 01:29

leetcode编程记录9 #543 Diameter of Binary Tree

标签(空格分隔): leetcode


这次是一道关于树的题目,这是一个比较简单的题目,找出在树中的一条最长的路径的长度。题目如下:

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 diameterOfBinaryTree(TreeNode* root) {        result = 0;       if (root != NULL) {        int example = height(root->left) + height(root->right);        return max(example, result);       } else {        return 0;       }    }//private:    int result;    int max(int a, int b) {        if (a > b) {            return a;        } else {            return b;        }    }    int height(TreeNode* root) {        if (root == NULL) {            return 0;        } else {            int left = height(root->left);            int right = height(root->right);            result = max(result, left + right);            return max(left, right) + 1;        }    }};
原创粉丝点击