考研算法
题目
题目要求
遍历二叉树
可以使用深度遍历和宽度遍历
深度遍历代码量较小
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int dfs(TreeNode *root,int path)
{
if (!root) return 0;//节点是否存在
if (!root->left and !root->right)//若为叶子节点
{
return root->val*path;
}
else return dfs(root->left,path+1)+dfs(root->right,path+1);//继续遍历
}
int pathSum(TreeNode* root) {
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
def dfs(root,path):
if root==None:return 0
if (root.left==None and root.right==None):
return root.val*path
else:
return dfs(root.left,path+1)+dfs(root.right,path+1)
class Solution:
def pathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
a=dfs(root,0)
return a