Description Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target. A valid path is from root node to any of the leaf nodes. Example Given a binary tree, and target = 5: 1 / \ 2 4 / \ 2 3 return [ [1, 2,…
Problem 1 [Balanced Binary Tree] Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Pr…
Description For the given binary tree, return a deep copy of it. Example Given a binary tree: 1 / \ 2 3 / \ 4 5 return the new binary tree with same structure and same value: 1 / \ 2 3 / \ 4 5 解题:链表复制.递归解法比较简单,代码如下: /** * Definition of TreeNode: * pu…
Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target. A valid path is from root node to any of the leaf nodes. Example Given a binary tree, and target = 5: 1 / \ 2 4 / \ 2 3 return [ [1, 2, 2], [1, 4]…
1.类中递归调用函数需要加self # 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 # @param sum, an integer # @return a boolean def hasPath…
Description You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1. A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of…
Description Given two binary strings, return their sum (also a binary string). Example a = 11 b = 1 Return 100 解题:二进制相加.我的思路是,先转成StringBuilder对象(reverse方法比较好用),因为相加是从最后开始,所以先用reverse方法倒转过来.和上一题类似,用carry变量表示进位,0为不进位,1为需要进一位.最后的结果再倒过来.具体细节标注在代码中,代码如下:…
Description Count how many 1 in binary representation of a 32-bit integer. Example Given 32, return 1 Given 5, return 2 Given 1023, return 9 Challenge If the integer is n bits with m 1 bits. Can you do it in O(m) time? 解题:很简单,但是要考虑范围的问题.代码如下: public…
Description Cosine similarity is a measure of similarity between two vectors of an inner product space that measures the cosine of the angle between them. The cosine of 0° is 1, and it is less than 1 for any other angle. See wiki: Cosine Similarity H…
Description Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node. Example Linked list is 1->2->3->4, and given node 3, delete the node in place 1->2->4 解题:删除指定的结点.由于java没有delete 或者 fr…