Open azl397985856 opened 2 years ago
class Solution { public int sumNumbers(TreeNode root) { if(root == null) return 0;
return dfs(root,0);
}
private int dfs(TreeNode root,int sum){
if(root == null) return 0;
if(root.left == null && root.right == null){
return sum * 10 + root.val;
}else if(root.left != null && root.right == null){
return dfs(root.left,sum * 10 + root.val);
}else if(root.left == null && root.right != null){
return dfs(root.right,sum * 10 + root.val);
}else{
return dfs(root.left,sum * 10 + root.val) + dfs(root.right,sum * 10 + root.val);
}
}
}
def sumNumbers(self, root: Optional[TreeNode]) -> int: def dfs(root, cur): if not root: return 0
if not root.left and not root.right:
return cur * 10 + root.val
return dfs(root.left, cur * 10 + root.val) + dfs(root.right, cur * 10 + root.val)
return dfs(root, 0)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
if not root:
return 0
def helper(node,nums):
if node:
nums.append(node.val)
if node.left:
helper(node.left,nums[:])
if node.right:
helper(node.right,nums[:])
if not node.right and not node.left:
temp = ''.join(map(str,nums))
print(temp)
self.ans.append(temp)
self.ans = []
nums = []
helper(root,nums)
print(self.ans)
result = list(map(int, self.ans))
return sum(result)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def dfs(root, cur):
if not root: return 0
if not root.left and not root.right: return cur * 10 + root.val
return dfs(root.left, cur * 10 + root.val) + dfs(root.right, cur * 10 + root.val)
return dfs(root, 0)
DFS
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root, current):
if not root:
return 0
#无子节点
if not root.left and not root.right:
return current * 10 + root.val
ans = dfs(root.left, current*10 + root.val)+ dfs(root.right, current*10 + root.val)
return ans
return dfs(root, 0)
时间复杂度:O(n) 空间复杂度:O(h)
def sumNumbers(self, root: TreeNode):
root_to_leaf = 0
stack = [(root, 0) ]
while stack:
root, curr_number = stack.pop()
if root is not None:
curr_number = curr_number * 10 + root.val
# if it's a leaf, update root-to-leaf sum
if root.left is None and root.right is None:
root_to_leaf += curr_number
else:
stack.append((root.right, curr_number))
stack.append((root.left, curr_number))
return root_to_leaf
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
result=[]
path=[root.val]
def backtracking(node):
if not node.left and not node.right:
result.append(self.convet_to_in(path))
return
if node.left:
path.append(node.left.val)
backtracking(node.left)
path.pop()
if node.right:
path.append(node.right.val)
backtracking(node.right)
path.pop()
backtracking(root)
return sum(result)
def convet_to_in(self,arr):
number=0
mag=1
for i in range(len(arr)-1,-1,-1):
number+=arr[i]*mag
mag*=10
return number
Time: O(n)
Space: O(n)
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
ans = 0
def dfs(node, cur_val):
nonlocal ans
cur_val = cur_val * 10 + node.val
if node.left:
dfs(node.left, cur_val)
if node.right:
dfs(node.right, cur_val)
if not node.left and not node.right:
ans += cur_val
return
dfs(root, 0)
return ans
'''
ans = 0
stack = [(root, root.val)]
while stack:
node, val = stack.pop()
if node.left:
leftval = val * 10 + node.left.val
stack.append((node.left, leftval))
if node.right:
rightval = val * 10 + node.right.val
stack.append((node.right, rightval))
if not node.left and not node.right:
ans += val
return ans
'''
1 dfs 2 bfs
# Bfs
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
# bfs, 每层记录当前的路径上的总和,到叶子的时候返回。
queue = collections.deque([(root, 0)])
res = 0
while queue:
node, value = queue.popleft()
if node.left:
queue.append((node.left, value * 10 + node.val))
if node.right:
queue.append((node.right, value * 10 + node.val))
if not node.left and not node.right:
res += value * 10 + node.val # 到叶子节点了,res (总路径和)= 这条历史路径和+他自己。
return res
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def dfs(root, cur):
if not root: return 0
if not root.left and not root.right: return cur * 10 + root.val
return dfs(root.left, cur * 10 + root.val) + dfs(root.right, cur * 10 + root.val)
return dfs(root, 0)
Time: O(n) #Q:dfs 时间复杂度为啥是O(n)呀? Space: O(h) # 树的高度
Time: O(n) Space:O(len(queue)) 最坏O(n)
class Solution {
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
private int helper(TreeNode root, int num) {
if(root == null) return 0;
if(root.left == null && root.right == null) {
return num * 10 + root.val;
}
return helper(root.left, num * 10 + root.val) + helper(root.right, num * 10 + root.val);
}
}
复杂度分析
思路 dfs 获取从根节点开始的每个数字,规律是 number = number * 10 + k。
代码 function sumNumbers(root: TreeNode | null): number { let ans = 0; const dfs = (root: TreeNode, num: number) => { num = num * 10 + root.val; if (!root.left && !root.right) ans += num; if (root.left) dfs(root.left, num); if (root.right) dfs(root.right, num); }; if (root) dfs(root, 0); return ans; } 分析 时间复杂度:O(n) 空间复杂度:O(n)
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
ans = 0
stack = collections.deque()
stack.append((root, root.val))
while stack:
node, val = stack.popleft()
if not node.left and not node.right:
ans += val
if node.left:
stack.append((node.left, val * 10 + node.left.val))
if node.right:
stack.append((node.right, val * 10 + node.right.val))
return ans
def sumNumbers(self, root: Optional[TreeNode]) -> int:
'''
def dfs(node, value):
if not node.left and not node.right:
return value
if not node.left and node.right:
return dfs(node.right, value*10 + node.right.val)
if node.left and not node.right:
return dfs(node.left, value*10 + node.left.val)
return dfs(node.left, value*10 + node.left.val) + dfs(node.right, value*10 + node.right.val)
return dfs(root, root.val)
'''
stack = []
ans = 0
stack.append((root, root.val))
while stack:
node, value = stack.pop()
if not node.left and not node.right:
ans += value
if node.right:
stack.append((node.right, value*10 + node.right.val))
if node.left:
stack.append((node.left, value*10 + node.left.val))
return ans
DFS Time complexity O(n) Space complexity O(h) BFS Time complexity O(n) Space complexity O(q), q为stack长度,最坏情况为O(n)
class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 if root.left!=None: root.left.val=root.val10+root.left.val if root.right!=None: root.right.val=root.val10+root.right.val if not root.left and not root.right: return root.val return self.sumNumbers(root.left)+self.sumNumbers(root.right)
递归
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
res = 0
path = []
def backtrace(root):
nonlocal res
if not root: return # 节点空则返回
path.append(root.val)
if not root.left and not root.right: # 遇到了叶子节点
res += get_sum(path)
if root.left: # 左子树不空
backtrace(root.left)
if root.right: # 右子树不空
backtrace(root.right)
path.pop()
def get_sum(arr):
s = 0
for i in range(len(arr)):
s = s * 10 + arr[i]
return s
backtrace(root)
return res
复杂度分析
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def dfs(node):
if not node:
return
#只在是子节点的位置操作一次
if not node.left and not node.right:
# 为什么要在这里在添加一次呢,其实是去重
# 因为当如果是子节点,左右子树都为空会重复添加解释如下
# 在这个判断中if not node:return 我们self.res.append的话
# 当左子树为空进来的时候添加一次
# 回溯进入右子树进来的时候也为空所以又添加一次
self.que.append(node.val)
self.res.append(int(''.join([str(i) for i in self.que])))
self.que.pop()
return
self.que.append(node.val)
dfs(node.left)
dfs(node.right)
self.que.pop()
self.res = []
self.que = []
dfs(root)
return sum(self.res)
很显然可以用DFS
和BFS
的方法解决。
DFS
很简单。
BFS
:
sum
中;/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int prev) {
if (root == null) return 0;
prev = 10 * prev + root.val;
if (root.left == null && root.right == null) return prev;
return dfs(root.left, prev) + dfs(root.right, prev);
}
}
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> prevList = new LinkedList<>();
queue.offer(root);
prevList.offer(root.val);
int sum = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int num = prevList.poll();
if (node.left == null && node.right == null) {
sum += num;
} else {
if (node.left != null) {
prevList.offer(10 * num + node.left.val);
queue.offer(node.left);
}
if (node.right != null) {
prevList.offer(10 * num + node.right.val);
queue.offer(node.right);
}
}
}
return sum;
}
}
DFS:
BFS:
class Solution {
private int result = 0;
public int sumNumbers(TreeNode root) {
helper(root, 0);
return result;
}
private void helper(TreeNode node, int prePathVal) {
// base rule
int currPathVal = prePathVal * 10 + node.val;
if (node.left == null && node.right == null) {
result += currPathVal;
return;
}
if (node.left != null) {
helper(node.left, currPathVal);
}
if (node.right != null) {
helper(node.right, currPathVal);
}
}
}
time: O(n) - n is the number of nodes space: O(tree_height)
这题和二叉树的所有路径其实是一摸一样的,两题可以一起做。
其实就是遍历所有路劲,无非就是设置一个数记录往下遍历和回溯后路径上数的变化。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void DFS(TreeNode* root,int& sum, int &cur){
cur = cur*10+root->val;
if(root->left == nullptr && root->right == nullptr) sum += cur;
if(root->left){
DFS(root->left,sum,cur);
cur = cur/10;
}
if(root->right){
DFS(root->right,sum,cur);
cur = cur/10;
}
}
int sumNumbers(TreeNode* root) {
int sum = 0;
int cur = 0;
DFS(root,sum,cur);
return sum;
}
};
复杂度分析
时间复杂度:O(n) n为节点个数
空间复杂度:O(h) h为树的深度,其实就是递归栈
recursion
class Solution {
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
public int helper(TreeNode root, int i){
if(root == null){
return 0;
}
int ans = i * 10 + root.val;
if(root.left == null && root.right == null){
return ans;
}
return helper(root.left, ans) + helper(root.right, ans);
}
}
复杂度分析
思路:DFS class Solution { public int sumNumbers(TreeNode root) { return dfs(root,0); } public int dfs(TreeNode root,int pre){ if(root==null){ return 0; } int sum=pre*10 +root.val; if(root.left==null && root.right==null){ return sum; }else{ return dfs(root.left,sum)+dfs(root.right,sum); } } } 时间复杂度:O(n); 空间复杂度:O(n);
DFS
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
dfs(root, 0);
return sum;
}
private void dfs(TreeNode root, int pre) {
if (root.left == null && root.right == null) {
sum += pre;
return;
}
if (root.left != null) {
dfs(root.left, pre * 10 + root.left.val);
}
if (root.right != null) {
dfs(root.right, pre * 10 + root.right.val);
}
}
}
DFS:
因为递归栈的存在,所以通过递归到叶子节点,然后再向上累加,每次上一层则*10,从而完成数位提升。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
return dfs(root,0);
}
int dfs(TreeNode* root,int temp){
if(root==nullptr) return 0;
if(root->right==nullptr && root->left==nullptr) return temp*10+root->val;
return dfs(root->left,temp*10+root->val)+dfs(root->right,temp*10+root->val);
}
};
时间复杂度:O(n)
思路:
深度遍历树,按规则求出所有结点值,然后求和;
步骤:
左右子树的和为答案;
java
public int sumNumbers(TreeNode root) {
if(root == null){
return 0;
}
return sumNode(root,0);
}
public int sumNode(TreeNode root, int sumVal){
int ans = sumVal+root.val;
if(root.left==null&&root.right==null){
return ans;
}
ans *= 10;
int leftAns = 0,rightAns = 0;
if(root.left!=null){
leftAns = sumNode(root.left,ans);
}
if(root.right!=null){
rightAns = sumNode(root.right,ans);
}
return leftAns+rightAns;
}
时间:O(n),n为结点数;
空间:O(n),最坏情况,输的高度为结点数;
https://leetcode.com/problems/sum-root-to-leaf-numbers/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
dfs(root, 0);
return sum;
}
private void dfs(TreeNode root, int last){
if(root == null){
return;
}
if(root.left == null && root.right == null){
sum += last * 10 + root.val;
return;
}
dfs(root.left, last * 10 + root.val);
dfs(root.right, last * 10 + root.val);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Pair{
TreeNode node;
int last;
public Pair(TreeNode n, int l){
node = n;
last = l;
}
}
class Solution {
public int sumNumbers(TreeNode root) {
if(root == null){
return 0;
}
int sum = 0;
Queue<Pair> queue = new LinkedList<>();
queue.offer(new Pair(root, 0));
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
Pair cur = queue.poll();
TreeNode curNode = cur.node;
int last = cur.last;
if(curNode.left == null && curNode.right == null){
sum += last * 10 + curNode.val;
}
if(curNode.left != null){
queue.offer(new Pair(curNode.left, last * 10 + curNode.val));
}
if(curNode.right != null){
queue.offer(new Pair(curNode.right, last * 10 + curNode.val));
}
}
}
return sum;
}
}
/**
@return {number} / var sumNumbers = function(root) { let sum = 0 function plus(node, c) { if (!node.left && !node.right) { sum += c 10 + node.val return }
node.left && plus(node.left, c 10 + node.val) node.right && plus(node.right, c 10 + node.val)
}
plus(root, 0) return sum };
思路 求从根到叶子的路径之和,那我们只需要把每条根到叶子的路径找出来,并求和即可,这里用 DFS 去解
class Solution { public: int sum = 0; int sumNumbers(TreeNode* root) { dfs(root, 0); return sum; }
void dfs(TreeNode* root, int num) {
if (!root) return;
if (!root->left && !root->right) {
sum += num * 10 + root->val;
return;
}
dfs(root->left, num * 10 + root->val);
dfs(root->right, num * 10 + root->val);
}
};
时间复杂度:O(n) 空间复杂度:O(h)
class Solution: def sumNumbers(self, root: Optional[TreeNode]) -> int: return self.dfs(root, 0)
def dfs(self, root, prevtotal):
if not root:
return 0
total = 10*prevtotal + root.val
if not root.left and not root.right:
return total
else:
return self.dfs(root.left, total) + self.dfs(root.right, total)
class Solution {
public:
int sumNumbers(TreeNode* root) {
int ret =0;
dfs(root, 0, ret);
return ret;
}
void dfs(TreeNode* root, int val, int& ret)
{
if(root==NULL)
return;
int currentVal = val*10 + root->val;
if(root->left == NULL && root->right==NULL)
{
ret += (currentVal);
return ;
}
dfs(root->left, currentVal, ret);
dfs(root->right, currentVal, ret);
}
};
给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。 每条从根节点到叶节点的路径都代表一个数字:
例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。 计算从根节点到叶节点生成的 所有数字之和 。
叶节点 是指没有子节点的节点。
dfs遍历树,一旦到达叶子结点,就把累加的值存进记忆表res中,程序结束后遍历res线性表,求元素和即可
class Solution {
public int sumNumbers(TreeNode root) {
List<Integer> res = new ArrayList<>();
int totalNum = 0;
sumNumbers(root, 0, res);
for(int num : res){
totalNum += num;
}
return totalNum;
}
private void sumNumbers(TreeNode root, int totalNum, List<Integer> res){
if(root == null){
return;
}
totalNum = totalNum * 10 + root.val;
//check whether leaf node
if(root.left == null && root.right == null){
res.add(totalNum);
}
sumNumbers(root.left, totalNum, res);
sumNumbers(root.right, totalNum, res);
return;
}
}
时间复杂度:$O(n)$
因为每个结点都要遍历一遍
空间复杂度:$O(height)$
height是树的高度,这也是这个递归栈所需要的最大深度
DFS
class Solution {
public:
int res=0;
int sumNumbers(TreeNode* root) {
if(root) dfs(root,0);
return res;
}
void dfs(TreeNode *root, int number){
number=number*10 + root->val;
if(!root->left&&!root->right) res+=number;
if(root->left) dfs(root->left,number);
if(root->right) dfs(root->right,number);
}
};
时间复杂度 O(n) 空间复杂度 O(lgn)
class Solution: def sumNumbers(self, root: TreeNode) -> int:
c = 0
def traversal(root, w):
nonlocal c
if not root:
return 0
if not root.left and not root.right:
c += w*10 + root.val
else:
w = w*10 + root.val
traversal(root.left, w)
traversal(root.right, w)
k = 0
traversal(root, k)
return c
# on on
递归;深度优先搜索
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int prevSum){
if (root == null){
return 0;
}
int sum = prevSum * 10 +root.val;
if(root.left == null && root.right == null){
return sum;
}else {
return dfs(root.left, sum) + dfs(root.right, sum);
}
}
}
复杂度分析 时间复杂度:$0(N)$ 空间复杂度:$0(N)$
回溯
class Solution {
public int sumNumbers(TreeNode root) {
path+=root.val;
System.out.println(path.toString());
backtracking(root);
int res=0;
for(Integer i:list){
res+=i;
}
return res;
}
Integer path=0;
List<Integer> list=new ArrayList<>();
private void backtracking(TreeNode root){
if(root.left==null && root.right==null){
list.add(path);
return;
}
if(root.left!=null){
path=path*10+root.left.val;
backtracking(root.left);
path/=10;
}
if(root.right!=null){
path=path*10+root.right.val;
backtracking(root.right);
path/=10;
}
}
}
时间复杂度:O(n) 空间复杂度:O(h)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function(root) {
let arr=[];
let source = (root,str)=>{
if(!root) return
str+=root.val
if(!root.left&&!root.right){
arr.push(str)
}else{
source(root.right,str)
source(root.left,str)
}
}
source(root,'')
let res = 0;
arr.forEach(item=>res+=1*item)
return res
};
class Solution { public int sumNumbers(TreeNode root) { return traverse(root, 0); }
public int traverse(TreeNode root, int sum) {
if (root == null) return 0;
sum = sum * 10 + root.val;
if (root.left == null && root.right == null) {
return sum;
} else {
return traverse(root.left, sum) + traverse(root.right, sum);
}
}
}
思路 dfs
代码
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
return self.dfs(root, 0)
def dfs(node, last_score):
if not node:
return 0
score = 10*last_score + node.val
if not node.left and not node.right:
return score
return dfs(node.left, score) + dfs(node.right, score)
复杂度 时间 O(n) 空间 O(n)
class Solution {
int res = 0;
public int sumNumbers(TreeNode root) {
dfs(root,0);
return res;
}
public void dfs(TreeNode root,int num){
if(root==null)return;
if(root.left==null&&root.right==null){
res += num*10+root.val;
return ;
}
dfs(root.left,num*10+root.val);
dfs(root.right,num*10+root.val);
}
}
深度优先搜索
当节点($root)
不存在时返回0;当节点($root)
存在时,如果左节点($root->left)
不存在和右节点($root->right)
不存在时,返回当前节点($root)
的值($root->val)
*10加上之前的值$current
(初始值0);然后将左子树和右子树按照上面的方法计算然后相加,即可得到最终答案
<?php
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution
{
/**
* @param TreeNode $root
* @return Integer
*/
function sumNumbers($root)
{
return $this->dfs($root, 0);
}
/**
* 深度优先搜索
*
* @param $root
* @param $current
* @return float|int
*/
private function dfs($root, $current)
{
if (!$root) {
return 0;
}
$currentSame = $current * 10 + $root->val;
if (!$root->left && !$root->right) {
return $currentSame;
}
return $this->dfs($root->left, $currentSame) + $this->dfs($root->right, $currentSame);
}
}
使用递归调用,每一次将root累计计算的结果,传入计算,如果根为空,返回0。 如果左右两个节点都为空,返回传入的num即可
class Solution {
public:
int sumNode(int num, TreeNode *root)
{
// 如果进来,节点为空,直接返回传入的参数。
if(nullptr == root){
return 0;
}
num = num * 10 + root->val;
// 如果左右节点都为空, 直接返回num
if (nullptr == root->left && nullptr == root->right)
{
return num;
}
else
{
// 不为空时继续递归计算
return sumNode(num, root->left) + sumNode(num, root->right);
}
}
int sumNumbers(TreeNode *root)
{
return sumNode(0, root);
}
};
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def dfs(root: TreeNode, prevTotal: int) -> int:
if not root:
return 0
total = prevTotal * 10 + root.val
if not root.left and not root.right:
return total
else:
return dfs(root.left, total) + dfs(root.right, total)
return dfs(root, 0)
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
def dfs(root, cur):
if not root: return 0
if not root.left and not root.right: return cur * 10 + root.val
return dfs(root.left, cur * 10 + root.val) + dfs(root.right, cur * 10 + root.val)
return dfs(root, 0)
复杂度
# DFS
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root, pre):
if not root:
return 0
sum_ = pre * 10 + root.val
if not root.right and not root.left:
return sum_
else:
return dfs(root.right, sum_)+ dfs(root.left, sum_)
return dfs(root, 0)
# BFS
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
que1 = [root]
que2 = [root.val]
sum_ = 0
while que1:
node = que1.pop()
num = que2.pop()
l, r = node.right, node.left
if not l and not r:
sum_ += num
else:
if l:
que1.append(l)
que2.append(num * 10 + l.val)
if r:
que1.append(r)
que2.append(num * 10 + r.val)
return sum_
到 leaf node 的时候成数,所以自然的想到了使用 DFS。
自己实现的时候太死板,只想到到底之后才算值,所以使用了 stack 对路径中的数进行储存。 完全没有必要。
class Solution {
public:
int sumNumbers(TreeNode* root) {
// dfs, with level info
stack<int> digits;
return dfs(root, digits);
}
int dfs(TreeNode* root, stack<int> &digits) {
int sum = 0;
if (!root) return 0;
if (!root->left && !root->right) { // leaf node
stack<int> tmp;
int mul = 1;
sum = root->val;
while (!digits.empty()) {
int d = digits.top();
digits.pop();
tmp.push(d);
mul *= 10;
sum += d * mul;
}
while(!tmp.empty()) {
digits.push(tmp.top());
tmp.pop();
}
} else {
digits.push(root->val);
sum += dfs(root->left, digits);
sum += dfs(root->right, digits);
digits.pop();
}
return sum;
}
};
复杂度分析
var sumNumbers = function(root) {
return totalNum(root,0);
};
function totalNum(root,num){
if(!root) return 0;
num = root.val+num*10;
if(root.left==null&&!root.right) return num;
return totalNum(root.left,num) + totalNum(root.right,num);
}
思路:深度遍历,累加所有节点 代码:
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function(root) {
var res = 0;
const dfs = function(root, sum) {
if(root == null) return;
sum = sum * 10 + root.val;
if(!root.left && !root.right) res = res + sum;
dfs(root.left, sum);
dfs(root.right, sum);
};
dfs(root, 0);
return res;
};
复杂度分析:
①深度优先
求根节点到叶节点数字之和可以表示为从根节点到左子树的叶节点数字之和加上从根节点到右子树的叶节点数字之和。到某节点的和可以表示为父节点的和*10+子节点的值,递归的出口为当结点为null时返回0,当结点的左子树和右子树皆为0时,返回sum。
②广度优先
自顶向下,用两个队列分别保存结点,和从根节点到该结点的和。每次从队列首部弹出一个结点,如果其左子树和右子树为空,则将和加入到sum中,否则将其左子树和右子树的结点以及和分别加入队列。
var sumNumbers = function(root) {
return dfs(root, 0);
};
function dfs(root, sum){
if(!root) return 0;
sum = sum * 10 + root.val;
if(!root.right && !root.left){
return sum;
}else{
return dfs(root.right, sum) + dfs(root.left, sum);
}
}
var sumNumbers = function(root){
let q1 = [], q2 = [];
let sum = 0;
q1.push(root);
q2.push(root.val);
while(q1.length){
let node = q1.shift();
let val = q2.shift();
let left = node.left;
let right = node.right;
if(left){
q1.push(left);
q2.push(val * 10 + left.val);
};
if(right){
q1.push(right);
q2.push(val * 10 + right.val);
};
if(!left && !right){
sum += val;
}
}
return sum;
}
复杂度分析
动态规划,自底向上,
最简子结构:从叶子节点的情况
逻辑关系:子树和之间的关系
实现方式:递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int helper(TreeNode*root ,int sum){
if(root==nullptr)return 0;//空节点时的值
int ret = root->val + 10*sum;//越往下,就需要在将基数增加
if(root->left == nullptr && root->right == nullptr)
return ret;//若为叶子节点,则返回,因此而结束
int left = helper(root->left,ret);//有子节点,则依次递归处理:计算左子树
int right = helper(root->right,ret);//有子节点,则依次递归处理:计算右子树
return left+right;//返回两子树和
}
int sumNumbers(TreeNode* root) {
return helper(root,0);
}
};
复杂度分析
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans = 0;
int sumNumbers(TreeNode* root) {
dfs(root, 0);
return ans;
}
void dfs(TreeNode* root, int num) {
num = num * 10 + root->val;
if (!root->left && !root->right) ans += num;
if (root->left) dfs(root->left, num);
if (root->right) dfs(root->right, num);
}
};
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int prevSum) {
if (root == null) {
return 0;
}
int sum = prevSum * 10 + root.val;
if (root.left == null && root.right == null) {
return sum;
} else {
return dfs(root.left, sum) + dfs(root.right, sum);
}
}
}
129. 求根到叶子节点数字之和
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/
前置知识
题目描述
例如,从根到叶子节点路径 1->2->3 代表数字 123。
计算从根到叶子节点生成的所有数字之和。
说明: 叶子节点是指没有子节点的节点。
示例 1:
输入: [1,2,3] 1 / \ 2 3 输出: 25 解释: 从根到叶子节点路径 1->2 代表数字 12. 从根到叶子节点路径 1->3 代表数字 13. 因此,数字总和 = 12 + 13 = 25. 示例 2:
输入: [4,9,0,5,1] 4 / \ 9 0 / \ 5 1 输出: 1026 解释: 从根到叶子节点路径 4->9->5 代表数字 495. 从根到叶子节点路径 4->9->1 代表数字 491. 从根到叶子节点路径 4->0 代表数字 40. 因此,数字总和 = 495 + 491 + 40 = 1026.