Find Bottom Left Tree Value宽度优先遍历算法详解
来源:互联网 发布:修改游戏数据 编辑:程序博客网 时间:2024/06/11 18:17
问题详见: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 3Output: 1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7Output: 7
Note: You may assume the tree (i.e., the given root node) is not NULL.
解题思路:
由题目可知该问题可以直接采用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: 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; }};
提交运行结果:
0 0
- Find Bottom Left Tree Value宽度优先遍历算法详解
- leetcode 513. Find Bottom Left Tree Value 一个简单的DFS深度优先遍历
- Find Largest Value in Each Tree Row宽度优先遍历算法详解
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- 算法课 第四周 Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- 513:find bottom left tree value
- java泛型(三)、通配符的使用
- Linux命令基础7-rmdir和rm命令
- Higher Math
- 11 qt多线程
- 572. Subtree of Another Tree
- Find Bottom Left Tree Value宽度优先遍历算法详解
- Django学习笔记之创建工程、模板,标签
- 股票价格综合指数(上证指数、深证指数)笔记
- [计算机视觉][神经网络与深度学习]Faster R-CNN配置及其训练教程
- easyui的一些总结(一)
- P1193 导游2
- 选择法排序
- android基础(Fragment)
- [计算机视觉][神经网络与深度学习]SSD安装及其训练教程