1、Merge Two Binary Trees
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
题意:将两个二叉树合并成一个,要求如果相同节点上都有值,则将其相加,如果只有一个节点有值,则以改值填充,如果都没值,该节点为空。
思路:以一个树为主树,另一个树为从树,同时遍历两个树,如果两个节点都有值,则将从树的值加到主树上,如果从树有值,主树为空,则使用从树的值,填充该节点,如果从树为空,则不用管。
代码实现,使用递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 != null && t2 != null) {
t1.left = mergeTrees(t1.left,t2.left);
t1.right = mergeTrees(t1.right,t2.right);
t1.val += t2.val;
return t1;
}
return t1 == null ? t2 : t1;
}
}
2、leetcode Counting Bits
leetcode Counting Bits
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
题意:给定一个整数num,输出0~num中每个数的二进制1的个数
法1:仔细分析一下可发现当一个数是2的整数幂的时候,二进制1的个数为1。之后就是前一个序列+1,如:
1、2(0010) = 1
2、3(0011) = 2(0010) + 1(0001) = 2
3、6(0110) = 4(0100) + 2(0010) = 1 + 1 = 2
4、7(0111) = 4(0100) + 3(0011) = 1 + 2 = 3
5、9 (1001) = 8(1000) + 1(0001) = 1 + 1 = 2
就是把一个数分解为小于它的最大2的整数幂 + x
代码实现:
public static int[] countBits(int num) {
int[] res = new int[num + 1];
int pow2 = 1,before = 1;
for(int i = 1;i<=num;i++){
if(pow2 == i) {
res[i] = before = 1;
pow2 <<= 1;
} else {
res[i] = res[before] + 1;
before++;
}
}
return res;
}
法2:一个数*2就是把它的二进制全部左移1位,也就是说1的个数是相等的,那我我们如果将一个数右移以为呢?如果这个数是偶数,右移1位正好是num/2,如果是奇数,则是num/2 + 1。我们可以得到以下公式:
res[i] = res[i >> 1] + (i & 1);(如果是奇数,i & 1得到1,如果是偶数i & 1得到0)
我们的代码可以这样改写:
public static int[] countBits2(int num) {
int[] res = new int[num + 1];
for (int i = 1; i <= num; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
网友评论