Find Bottom Left Tree Value宽度优先遍历算法详解
2017-05-13 21:25
309 查看
问题详见:Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.Example 1:
Input: 2 / \ 1 3 Output: 1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7
Note: You may assume the tree (i.e., the given root node) is not NULL.
解题思路:
由题目可知该问题可以直接采用BFS的方法对其进行查找,通过使用队列的插入和删除操作直至找到二叉树中最后一行的最左边的元素,其时间复杂度为O(n)。下面是算法的C++代码和提交结果图。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: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> q; queue<int> level; q.push(root); level.push(0); int m=0; while(q.size()){ TreeNode *r = q.front(); q.pop(); int l = level.front(); level.pop(); if(r->left) { q.push(r->left); level.push(l+1); } if(r->right){ q.push(r->right); level.push(l+1); } if(l > m){ m = l; root = r; } } return root->val; } };
提交运行结果:
相关文章推荐
- Find Largest Value in Each Tree Row宽度优先遍历算法详解
- 第十周算法分析与设计: Find Bottom Left Tree Value
- 算法分析与设计丨第四周丨LeetCode(7)——Find Bottom Left Tree Value(Medium)
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- 算法课 第四周 Find Bottom Left Tree Value
- LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
- LeetCode: Find Bottom Left Tree Value
- leetcode513 FindBottomLeftTreeValue Java
- Find Bottom Left Tree Value
- [LeetCode]Find Bottom Left Tree Value 寻找二叉树最左树叶的值
- 【LeetCode】Find Bottom Left Tree Value 解题报告
- Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value
- Find Bottom Left Tree Value |找到二叉树最后一层的最左边的节点的值
- Find Bottom Left Tree Value
- [LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- 【513】 Find Bottom Left Tree Value
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value