第十四周LeetCode

来源:互联网 发布:新媒体传播 网络传播 编辑:程序博客网 时间:2024/05/16 05:42

题目
Longest Univalue Path
难度   Easy

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

Note: The length of path between two nodes is represented by the number of edges between them.

Example 1:
Input:

          5         / \        4   5       / \   \      1   1   5

Output:
2

Example 2:

Input:

          1         / \        4   5       / \   \      4   4   5

Output:
2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

实现思路

利用递归思想实现。对于每一个结点,求它的左子树和右子树的最长路径,如果结点的左节点值与该结点值相同,那么该节点的最长路径为左子树最长路径长度加一;同理如果与右子树的值相同,那么该节点的最长路径为右子树最长路径加一,如果左右子树的值都与该节点值相同,则该节点的最长路径为左子树最长路径加右子树最长路径。求得所有节点的最长路径后,取最大值返回。注意最长路径用边数表示。

实现代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */     int longestUnivaluePath(TreeNode* root) {        queue<TreeNode*> q;        if (root) q.push(root);        int depth;        int longest = 0;        while (!q.empty()) {            TreeNode* u = q.front();            q.pop();            depth = findLongest(u->left,u->val)+findLongest(u->right,u->val);            if (longest<depth) longest=depth;            if (u->left) q.push(u->left);            if (u->right) q.push(u->right);        }        return longest;    }    int findLongest(TreeNode* root, int val) {        if (!root || root->val != val) return 0;        int left = findLongest(root->left, val);        int right = findLongest(root->right, val);        return max(left,right)+1;    }
原创粉丝点击