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
  • 相关阅读:
    常用的长度单位
    HTML常用的列表标签
    html常用文本标签
    CSS选择器及优先级
    块级元素与内联元素
    移动端app打包
    内联框架
    Leetcode303.区域和检索-数组不可变
    Leetcode107.二叉树的层次遍历||
    Leetcode784.字母大小写全排列
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/7501620.html
Copyright © 2011-2022 走看看