zoukankan      html  css  js  c++  java
  • leetcode算法: Find Bottom Left Tree Value

    leetcode算法: Find Bottom Left Tree Value

    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.


    这道题 是 给我们一颗二叉树的根节点,让我们找到最后一层的最左边的节点。
    绞尽脑汁之后,利用二维数组把每个节点和所在层次扒下来了,但是还是太麻烦。看了其他大神的思路豁然开朗!

    大神的思路是:从右向左广度优先遍历!! 最后一个节点就是我们要的结果!!
    献上我的代码:
     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 
     8 class Solution(object):
     9     def findBottomLeftValue(self, root):
    10         """
    11         :type root: TreeNode
    12         :rtype: int
    13         """
    14         q = [root]
    15         while q:
    16             node = q.pop(0)
    17             if node.right is not None:
    18                 q.append(node.right)
    19             if node.left is not None:
    20                 q.append(node.left)
    21         return node.val
  • 相关阅读:
    Nginx 部署多个 web 项目(虚拟主机)
    Nginx 配置文件
    Linux 安装 nginx
    Linux 安装 tomcat
    Linux 安装 Mysql 5.7.23
    Linux 安装 jdk8
    Linux 安装 lrzsz,使用 rz、sz 上传下载文件
    springMVC 拦截器
    spring 事务
    基于Aspectj 注解实现 spring AOP
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501620.html
Copyright © 2011-2022 走看看