Find Largest Value in Each Tree Row宽度优先遍历算法详解
来源:互联网 发布:linux 如何进入grub 编辑:程序博客网 时间:2024/06/05 03:41
问题详见:Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
Example:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
解题思路:
由题目可知该问题也是同样应用BFS算法搜索每一层以得到每一层的最大值,其算法复杂度为
BFS:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> solution; void helper(TreeNode* node, int cl) { if (node == NULL) { return; } if (solution.size() < cl + 1) { solution.push_back(node->val); } else { if (solution[cl] < node->val) { solution[cl] = node->val; } } helper(node->left, cl+1); helper(node->right, cl+1); } vector<int> largestValues(TreeNode* root) { if(root == NULL) { return solution; } helper(root, 0); return solution; }};
提交运行结果:
0 0
- Find Largest Value in Each Tree Row宽度优先遍历算法详解
- leetcode 515. Find Largest Value in Each Tree Row 广度优先遍历BFS
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Tree——Find Largest Value in Each Tree Row
- 图(广度优先搜索)515. Find Largest Value in Each Tree Row[Middle]
- LeetCode 515 Find Largest Value in Each Tree Row(二叉树层序遍历)
- LeetCode 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- leetcode515: Find Largest Value in Each Tree Row
- LeetCode OJ 515. Find Largest Value in Each Tree Row
- 一个web应用的诞生(5)
- BZOJ 3995 [SDOI2015]道路修建
- 计算机网络(1)
- python发送邮件
- 一个web应用的诞生(4)
- Find Largest Value in Each Tree Row宽度优先遍历算法详解
- 汇编程序:简单的菜单
- Android高手进阶教程(三)之----Android 中自定义View的应用.
- solr之commit和softcommit
- 一个web应用的诞生(3)
- COMPUTER NETWORK
- 【C++】LeetCode 132. Palindrome Partitioning II
- python开发技能表格
- 犀牛软件rhinoceros的参数化设计插件草蜢grasshopper的安装