码迷,mamicode.com
首页 > 编程语言 > 详细

【LeetCode】【Python题解】Single Number & Maximum Depth of Binary Tree

时间:2014-07-20 15:27:41      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   递归   面试   遍历   

今天做了三道LeetCode上的简单题目,每道题都是用c++和Python两种语言写的,因为c++版的代码网上比较多,所以就只分享一下Python的代码吧,刚学完Python的基本语法,做做LeetCode的题目还是不错的,对以后找工作面试也有帮助!


刚开始就从AC率最高的入手吧!


1.Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

开始纠结于线性时间复杂度和不要额外的存储空间,思路是遍历一遍数组,想象成翻硬币,碰到一次就翻面,再碰到就翻回来了,剩下的那个仍是背面的就是只出现一次的。但是这种思路就势必要有额外的存储空间。后来看了别人的思路,原来全部异或就可以了,因为A XOR A =0,0 XOR any = any,简单多了。

class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        result = 0
        for i in A:
            result = result ^ i
        return result



2.Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


递归寻找左子树和右子树的深度,取二者较大的,再加上根的深度1,即为答案。

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return an integer
    def maxDepth(self, root):
        if root is None:
            return 0
        else:
            return max(self.maxDepth(root.left),self.maxDepth(root.right))+1


【LeetCode】【Python题解】Single Number & Maximum Depth of Binary Tree

标签:leetcode   python   递归   面试   遍历   

原文地址:http://blog.csdn.net/monkeyduck/article/details/37991201

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!