作者: 负雪明烛
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)的更多相关文章

  1. 【LeetCode】222. Count Complete Tree Nodes 解题报告(Python)

    [LeetCode]222. Count Complete Tree Nodes 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个 ...

  2. 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 ...

  3. [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 ...

  4. 【LeetCode】998. Maximum Binary Tree II 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  5. 【LeetCode】919. Complete Binary Tree Inserter 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址: https://leetcode. ...

  6. 【LeetCode】173. Binary Search Tree Iterator 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 保存全部节点 只保留左节点 日期 题目地址:http ...

  7. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

  8. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  9. 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归+队列 栈 日期 题目地址:https://lee ...

随机推荐

  1. perl练习——FASTA格式文件中序列GC含量计算&perl数组排序如何获得下标或者键

    一.关于程序: FUN:计算FASTA文件中每条序列中G和C的含量百分比,输出最大值及其id INPUT:FASTA格式文件 >seq1 CGCCGAGCGCTTGACCTCCAGCAAGACG ...

  2. Hosts文件详解

    一.缘由 关于我们工作室项目配置过程中,有一个重要但却容易被忽略的环节 - hosts文件的修改. 之前配置hosts文件的时候,只知道那么做就可以了,但并不知道其中的原因,由于开发任务的急迫,也就未 ...

  3. CentOS安装配置Hadoop 1.2.1(伪分布模式)

    CentOS安装配置Hadoop1.2.1 1.下载安装文件 下载2个安装文件 JAVA环境:jdk-6u21-linux-i586.bin Hadoop环境:hadoop-1.2.1.tar.gz ...

  4. kubernetes部署 flannel网络组件

    创建 flannel 证书和私钥flannel 从 etcd 集群存取网段分配信息,而 etcd 集群启用了双向 x509 证书认证,所以需要为 flanneld 生成证书和私钥. cat > ...

  5. 节省内存的循环banner(一)

    循环banner是指scrollview首尾相连,循环播放的效果,使用非常广泛.例如淘宝的广告栏等. 如果是简单的做法可以把所有要显示的图片全部放进一个数组里,创建相同个数的图片视图来显示图片.这样的 ...

  6. 【Spring Framework】Spring入门教程(六)Spring AOP使用

    Spring的AOP 动态代理模式的缺陷是: 实现类必须要实现接口 -JDK动态代理 无法通过规则制定拦截无需功能增强的方法. Spring-AOP主要弥补了第二个不足,通过规则设置来拦截方法,并对方 ...

  7. 【Services】【Web】【apr】安装apr

    1. 基础: 1.1 描述:apr全称Apache Portable Runtime,常用于与ssl相关的环境支持,比如openssl,httpd,nginx,tomcat 1.2 链接: 官方网站: ...

  8. promise ,async 小记

    Promise Promise 对象用于表示一个异步操作的最终状态(完成或失败),以及该异步操作的结果值. 摇色子游戏,随机1-6的一个整数,并且将其返回. function fn() { retur ...

  9. jquery:iframe里面的元素怎样触发父窗口元素的事件?

    例如父窗口定义了一个事件. top: $(dom1).bind('topEvent', function(){}); 那么iframe里面的元素怎样触发父窗口dom1的事件呢?这样吗? $(dom1, ...

  10. 加密解密、食谱、新冠序列,各种有趣的开源项目Github上都有

    Github上是我们程序员学习开源代码.提升编程技巧的好地方.好学校,但是除了学习,小伙伴们有没有发现过Github上一些特别有意思的项目呢? 今天TJ君就来和大家分享几个自认为特别有趣的开源项目: ...