作者: 负雪明烛
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:

  1. Input:
  2. 2
  3. / \
  4. 1 3
  5. Output:
  6. 1

Example 2:

  1. Input:
  2. 1
  3. / \
  4. 2 3
  5. / / \
  6. 4 5 6
  7. /
  8. 7
  9. Output:
  10. 7

Note: You may assume the tree (i.e., the given root node) is not NULL.

题目大意

求一个二叉树最下面一层的最左边节点。

解题方法

BFS

这就是所谓的BFS算法。广度优先搜索,但是搜索的顺序是有要求的,因为题目要最底层的叶子节点的最左边的叶子,那么进入队列的顺序就是先右节点再左节点,这样能把每层的节点都能从右到左过一遍,那么用一个int保存最后的节点值就可以了。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int findBottomLeftValue(TreeNode root) {
  12. int ans = 0;
  13. Queue<TreeNode> tree = new LinkedList<TreeNode>();
  14. tree.offer(root);
  15. while(!tree.isEmpty()){
  16. TreeNode temp = tree.poll();
  17. if(temp.right != null){
  18. tree.offer(temp.right);
  19. }
  20. if(temp.left != null){
  21. tree.offer(temp.left);
  22. }
  23. ans = temp.val;
  24. }
  25. return ans;
  26. }
  27. }

Python做法是用层次遍历,用的是双向队列,所以注意append和popleft。代码如下:

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def findBottomLeftValue(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: int
  12. """
  13. q = collections.deque()
  14. q.append(root)
  15. res = []
  16. while q:ruxai
  17. size = len(q)
  18. level = []
  19. for i in range(size):
  20. node = q.popleft()
  21. if not node: continue
  22. level.append(node.val)
  23. q.append(node.left)
  24. q.append(node.right)
  25. if level:
  26. res.append(level)
  27. return res[-1][0]

使用C++用的是BFS版本的层次遍历,代码如下:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int findBottomLeftValue(TreeNode* root) {
  13. queue<TreeNode*> q;
  14. q.push(root);
  15. vector<vector<int>> res;
  16. while (!q.empty()) {
  17. int size = q.size();
  18. vector<int> level;
  19. for (int i = 0; i < size; i++) {
  20. TreeNode* node = q.front(); q.pop();
  21. if (!node) continue;
  22. level.push_back(node->val);
  23. q.push(node->left);
  24. q.push(node->right);
  25. }
  26. if (!level.empty()) {
  27. res.push_back(level);
  28. }
  29. }
  30. return res[res.size() - 1][0];
  31. }
  32. };

DFS

使用DFS很简单了,直接把每一层的元素放到list里面,然后取出最后层的第一个节点即可。至于子树的遍历顺序,需要保证先遍历左子树再遍历右子树,这样才能把最下面一层的最左边节点放到最左侧,至于根节点的值在哪个位置进行append是不重要的。

python代码如下:

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def findBottomLeftValue(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: int
  12. """
  13. res = []
  14. self.dfs(root, res, 0)
  15. return res[-1][0]
  16. def dfs(self, root, res, level):
  17. if not root: return
  18. if level == len(res): res.append([])
  19. res[level].append(root.val)
  20. self.dfs(root.left, res, level + 1)
  21. self.dfs(root.right, res, level + 1)

C++代码需要注意的是,我们应该对res传引用进来,否则不能对外部变量进行更改。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int findBottomLeftValue(TreeNode* root) {
  13. dfs(root, res, 0);
  14. return res[res.size() - 1][0];
  15. }
  16. private:
  17. vector<vector<int>> res;
  18. void dfs(TreeNode* root, vector<vector<int>>& res, int level) {
  19. if (!root) return;
  20. if (level == res.size()) res.push_back({});
  21. res[level].push_back(root->val);
  22. dfs(root->left, res, level + 1);
  23. dfs(root->right, res, level + 1);
  24. }
  25. };

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. 55. Binary Tree Preorder Traversal

    Binary Tree Preorder Traversal My Submissions QuestionEditorial Solution Total Accepted: 119655 Tota ...

  2. 【PS算法理论探讨一】 Photoshop中两个32位图像混合的计算公式(含不透明度和图层混合模式)。

    大家可以在网上搜索相关的主题啊,你可以搜索到一堆,不过似乎没有那一个讲的很全面,我这里抽空整理和测试一下数据,分享给大家. 我们假定有2个32位的图层,图层BG和图层FG,其中图层BG是背景层(位于下 ...

  3. keil 报错 expected an identifier

    该报错是因为命名重复,可能是因为你加的头文件里面的命名和原程序中的有重复,所以产生了错误.

  4. Linux学习 - 流程控制

    一.if语句 1 单分支if条件语句 (1) if  [ 条件判断式 ];then 程序  fi (2) if [ 条件判断式 ] then 程序  fi 例:检测根分区的使用量 2 双分支if条件语 ...

  5. Output of C++ Program | Set 13

    Predict the output of following C++ program. 1 #include<iostream> 2 using namespace std; 3 4 c ...

  6. 初步接触Linux命令

    目录 虚拟机快照 1.首先将已经运行的系统关机 2.找到快照 拍摄快照 3.找到克隆 下一步 有几个快照会显示几个 4.克隆完成后 要修改一下IP 不然无法同时运行两个虚拟机系统 系统介绍 1.pin ...

  7. Linux提取命令grep 有这一篇就够了

    grep作为linux中使用频率非常高的一个命令,和cut命令一样都是管道命令中的一员.并且其功能也是对一行数据进行分析,从分析的数据中取出我们想要的数据.也就是相当于一个检索的功能.当然了,grep ...

  8. java 注解的几大作用及使用方法详解

    初学者可以这样理解注解:想像代码具有生命,注解就是对于代码中某些鲜活个体的贴上去的一张标签.简化来讲,注解如同一张标签. 在未开始学习任何注解具体语法而言,你可以把注解看成一张标签.这有助于你快速地理 ...

  9. 什么是mysql innodb cluster?

    目录 一.简介 二.特性 一.简介 MySQL InnoDB集群提供了一个集成的,本地的,HA解决方案.MySQL InnoDB集群由以下几部分组成: MySQL Servers with Group ...

  10. 解决用creact-react-app新建React项目不支持 mobx装饰器模式导致报错问题 。

    创建react项目 create-react-app mobx-demo cd my-app npm run start 使用react-app-rewired npm install customi ...