1022 Sum of Root To Leaf Binary Numbers
Last updated
Last updated
You are given the root
of a binary tree where each node has a value 0
or 1
. Each root-to-leaf path represents a binary number starting with the most significant bit.
For example, if the path is 0 -> 1 -> 1 -> 0 -> 1
, then this could represent 01101
in binary, which is 13
.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.
The test cases are generated so that the answer fits in a 32-bits integer.
Example 1:
Example 2:
Constraints:
The number of nodes in the tree is in the range [1, 1000]
.
Node.val
is 0
or 1
.
这题,一看path sum类型的,就想到递归了。看到它return int有想过从leaf到root,但发现好像不太好做。所以就从root到leaf了。因为数字都是从最左边开始算的,譬如,110 = 1 * 2 + 1 * 2 + 0 = 6。每当我们到达leaf的时候,算一下总和。每下去一层,就算一下现在这个要加的数字是多少。T:O(N),因为要经过每一个node,S:O(H),递归深度。
解法一:遍历然后加起来
解法二:Morris tree,在solution里看到了这个