【LeetCode】513. Find Bottom Left Tree Value 解题报告(Python & C++ & Java)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/find-bottom-left-tree-value/#/description
题目描述
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
这就是所谓的BFS算法。广度优先搜索,但是搜索的顺序是有要求的,因为题目要最底层的叶子节点的最左边的叶子,那么进入队列的顺序就是先右节点再左节点,这样能把每层的节点都能从右到左过一遍,那么用一个int保存最后的节点值就可以了。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int findBottomLeftValue(TreeNode root) {
int ans = 0;
Queue<TreeNode> tree = new LinkedList<TreeNode>();
tree.offer(root);
while(!tree.isEmpty()){
TreeNode temp = tree.poll();
if(temp.right != null){
tree.offer(temp.right);
}
if(temp.left != null){
tree.offer(temp.left);
}
ans = temp.val;
}
return ans;
}
}
Python做法是用层次遍历,用的是双向队列,所以注意append和popleft。代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
q = collections.deque()
q.append(root)
res = []
while q:ruxai
size = len(q)
level = []
for i in range(size):
node = q.popleft()
if not node: continue
level.append(node.val)
q.append(node.left)
q.append(node.right)
if level:
res.append(level)
return res[-1][0]
使用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;
q.push(root);
vector<vector<int>> res;
while (!q.empty()) {
int size = q.size();
vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode* node = q.front(); q.pop();
if (!node) continue;
level.push_back(node->val);
q.push(node->left);
q.push(node->right);
}
if (!level.empty()) {
res.push_back(level);
}
}
return res[res.size() - 1][0];
}
};
DFS
使用DFS很简单了,直接把每一层的元素放到list里面,然后取出最后层的第一个节点即可。至于子树的遍历顺序,需要保证先遍历左子树再遍历右子树,这样才能把最下面一层的最左边节点放到最左侧,至于根节点的值在哪个位置进行append是不重要的。
python代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = []
self.dfs(root, res, 0)
return res[-1][0]
def dfs(self, root, res, level):
if not root: return
if level == len(res): res.append([])
res[level].append(root.val)
self.dfs(root.left, res, level + 1)
self.dfs(root.right, res, level + 1)
C++代码需要注意的是,我们应该对res传引用进来,否则不能对外部变量进行更改。
/**
* 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) {
dfs(root, res, 0);
return res[res.size() - 1][0];
}
private:
vector<vector<int>> res;
void dfs(TreeNode* root, vector<vector<int>>& res, int level) {
if (!root) return;
if (level == res.size()) res.push_back({});
res[level].push_back(root->val);
dfs(root->left, res, level + 1);
dfs(root->right, res, level + 1);
}
};
Date
2017 年 4 月 13 日
【LeetCode】513. Find Bottom Left Tree Value 解题报告(Python & C++ & Java)的更多相关文章
- 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)
[LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...
- LN : leetcode 513 Find Bottom Left Tree Value
lc 513 Find Bottom Left Tree Value 513 Find Bottom Left Tree Value Given a binary tree, find the lef ...
- [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS
Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...
- 【LeetCode】998. Maximum Binary Tree II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- 【LeetCode】919. Complete Binary Tree Inserter 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址: https://leetcode. ...
- 【LeetCode】173. Binary Search Tree Iterator 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 保存全部节点 只保留左节点 日期 题目地址:http ...
- 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...
- 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...
- 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归+队列 栈 日期 题目地址:https://lee ...
随机推荐
- 55. Binary Tree Preorder Traversal
Binary Tree Preorder Traversal My Submissions QuestionEditorial Solution Total Accepted: 119655 Tota ...
- 【PS算法理论探讨一】 Photoshop中两个32位图像混合的计算公式(含不透明度和图层混合模式)。
大家可以在网上搜索相关的主题啊,你可以搜索到一堆,不过似乎没有那一个讲的很全面,我这里抽空整理和测试一下数据,分享给大家. 我们假定有2个32位的图层,图层BG和图层FG,其中图层BG是背景层(位于下 ...
- keil 报错 expected an identifier
该报错是因为命名重复,可能是因为你加的头文件里面的命名和原程序中的有重复,所以产生了错误.
- Linux学习 - 流程控制
一.if语句 1 单分支if条件语句 (1) if [ 条件判断式 ];then 程序 fi (2) if [ 条件判断式 ] then 程序 fi 例:检测根分区的使用量 2 双分支if条件语 ...
- Output of C++ Program | Set 13
Predict the output of following C++ program. 1 #include<iostream> 2 using namespace std; 3 4 c ...
- 初步接触Linux命令
目录 虚拟机快照 1.首先将已经运行的系统关机 2.找到快照 拍摄快照 3.找到克隆 下一步 有几个快照会显示几个 4.克隆完成后 要修改一下IP 不然无法同时运行两个虚拟机系统 系统介绍 1.pin ...
- Linux提取命令grep 有这一篇就够了
grep作为linux中使用频率非常高的一个命令,和cut命令一样都是管道命令中的一员.并且其功能也是对一行数据进行分析,从分析的数据中取出我们想要的数据.也就是相当于一个检索的功能.当然了,grep ...
- java 注解的几大作用及使用方法详解
初学者可以这样理解注解:想像代码具有生命,注解就是对于代码中某些鲜活个体的贴上去的一张标签.简化来讲,注解如同一张标签. 在未开始学习任何注解具体语法而言,你可以把注解看成一张标签.这有助于你快速地理 ...
- 什么是mysql innodb cluster?
目录 一.简介 二.特性 一.简介 MySQL InnoDB集群提供了一个集成的,本地的,HA解决方案.MySQL InnoDB集群由以下几部分组成: MySQL Servers with Group ...
- 解决用creact-react-app新建React项目不支持 mobx装饰器模式导致报错问题 。
创建react项目 create-react-app mobx-demo cd my-app npm run start 使用react-app-rewired npm install customi ...