LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
来源:互联网 发布:怎么免费做网络推广 编辑:程序博客网 时间:2024/06/11 03:34
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.
题目大意:给出一棵二叉树,求这棵树最底层最左边的节点值。
解题思路:又是一道层序遍历可以做的题。用数组保存每一层的第一个元素,最后返回数组中最后一个元素即可。
代码如下:
/** * 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) { levelOrderTraversal(root, 0, ans); return ans.back(); }private: queue<TreeNode*> que; vector<int> ans; //非递归版本 void levelOrderTraversal(TreeNode* root, vector<int>& ans) { if(root == nullptr) return ; TreeNode* tmp; que.push(root); int cur = 0; while(cur < que.size()) { int last = que.size(); tmp = que.front(); ans.push_back(tmp->val); while(cur < last) { tmp = que.front(); que.pop(); if(tmp->left) que.push(tmp->left); if(tmp->right) que.push(tmp->right); cur++; } cur = 0; } } //递归版本 void levelOrderTraversal(TreeNode* root, int depth, vector<int>& ans) { if(root == nullptr) return ; if(depth == ans.size()) ans.push_back(root->val); if(root->left) levelOrderTraversal(root->left, depth + 1, ans); if(root->right) levelOrderTraversal(root->right, depth + 1, ans); }};
阅读全文
0 0
- LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
- LeetCode #513: Find Bottom Left Tree Value
- Leetcode 513 Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value
- LeetCode#513 Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- [leetcode]513. Find Bottom Left Tree Value
- [leetcode] 513. Find Bottom Left Tree Value
- 【LeetCode】513. Find Bottom Left Tree Value
- Leetcode 513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- 【leetcode】 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value | LeetCode
- leetcode-513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- leetcode 513. Find Bottom Left Tree Value
- leetcode 513. Find Bottom Left Tree Value
- 模板方法之无法解析的外部符号
- PowerDesigner基础应用
- Java中级知识点
- 基于协程的异步爬虫
- POJ 1321 深搜 棋盘问题
- LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
- [BZOJ1514]添加括号
- [LeetCode] 122. Best Time to Buy and Sell Stock II
- spring读取配置文件的两种方式
- Android应用如何匹配不同的手机分辨率
- Socket小练习
- 管闲事的小明
- 禅
- Glide使用详解(一)