[LeetCode]Find Left Most Element

题目描述:

LeetCode 513. Find Left Most Element

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.

题目大意:

给定二叉树,返回末尾行的最左元素。

注意:你可以假设树非空。

解题思路:

二叉树的层次遍历

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 findLeftMostNode(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        qa = [root]
        while qa:
            qb = []
            for n in qa:
                if n.left: qb.append(n.left)
                if n.right: qb.append(n.right)
            if not qb: return qa[0].val
            qa = qb
        return None

 

本文链接:http://bookshadow.com/weblog/2017/02/12/leetcode-find-left-most-element/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码