LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
2017-07-19 19:49
597 查看
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Example 2:
Note: You may assume the tree (i.e., the given root node) is not NULL.
题目大意:给出一棵二叉树,求这棵树最底层最左边的节点值。
解题思路:又是一道层序遍历可以做的题。用数组保存每一层的第一个元素,最后返回数组中最后一个元素即可。
代码如下:
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.
题目大意:给出一棵二叉树,求这棵树最底层最左边的节点值。
解题思路:又是一道层序遍历可以做的题。用数组保存每一层的第一个元素,最后返回数组中最后一个元素即可。
代码如下:
/** * 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); } };
相关文章推荐
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- Leetcode 513 Find Bottom Left Tree Value
- LeetCode 515 Find Largest Value in Each Tree Row(二叉树层序遍历)
- leetcode 513 Find Bottom Left Tree Value C++
- [LeetCode]Find Bottom Left Tree Value 寻找二叉树最左树叶的值
- leetcode513 FindBottomLeftTreeValue Java
- leetcode 513 Find Bottom Left Tree Value
- LeetCode 513 Find Bottom Left Tree Value (BFS)
- [LeetCode]513 Find Bottom Left Tree Value(BFS)
- LeetCode - 513 - Find Bottom Left Tree Value
- 513:find bottom left tree value
- Week Training: 513 Find Bottom Left Tree Value
- 【LeetCode】Find Bottom Left Tree Value 解题报告
- LeetCode Find Bottom Left Tree Value [Medium]
- LeetCode: Find Bottom Left Tree Value
- Find Bottom Left Tree Value宽度优先遍历算法详解
- [LeetCode]Find Bottom Left Tree Value
- LeetCode——Find Bottom Left Tree Value
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value
- Find Bottom Left Tree Value |找到二叉树最后一层的最左边的节点的值