【LeetCode】Binary Tree Leaf Sum
来源:互联网 发布:厦门哪里有mac专柜 编辑:程序博客网 时间:2024/06/06 05:05
二叉树叶子节点之和
计算二叉树的叶子节点之和
样例
1
/ \
2 3
/
4
的叶子节点之和为 7。
标签
二叉树 二叉树遍历
(1)Java
//package BinaryTree;////public class TreeNode {// public int val;// public TreeNode left, right;//// public TreeNode(int val){// this.val = val;// this.left = null;// this.right = null;// } //}package BinaryTree;public class BinaryTreeLeafSum {//DFS public static int leafSum(TreeNode root){ if(root == null){//空 return 0; } if(root.left == null && root.right == null){//叶子节点: 直接返回其值 return root.val; } return leafSum(root.left) + leafSum(root.right);//递归分解: 普通节点,则递归求和 }}
(2)C++
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root the root of the binary tree * @return an integer */ int leafSum(TreeNode* root) { // Write your code here dfs(root); return sum; } void dfs(TreeNode* root) { if (root == NULL) return; if (root->left == NULL && root->right == NULL) sum += root->val; dfs(root->left); dfs(root->right); }private: int sum = 0;};
阅读全文
1 0
- 【LeetCode】Binary Tree Leaf Sum
- 【Leetcode】Path Sum from root to leaf in binary tree
- leetCode: binary tree sum
- LeetCode[Tree]: Sum Root to Leaf Numbers
- 【Leetcode】Given a binary tree, find all root-to-leaf paths whose sum equals a given number
- leetcode解题之57. Binary Tree Paths&129. Sum Root to Leaf Numbers Java版 (二叉树路径)
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode :: Sum Root to Leaf Numbers [tree、dfs]
- [leetcode][tree][dfs] Sum Root to Leaf Numbers
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- 虽然不简单但还是要学的JavaWeb—spring框架简介
- IOS开发中Category中动态添加属性
- CentOS 7 yum在线安装Java Web服务器环境(OpenJDK+Tomcat+MariaDB)
- 三种东西永远不要放到数据库里
- Ubuntu14.04系统登录密码正确进不了桌面死循环问题
- 【LeetCode】Binary Tree Leaf Sum
- 七.SpringBoot集成实例系列-多数据源mongodb+lombok(二)
- (M)DFS:491. Increasing Subsequences
- jQuery jsonp
- javascript执行上下文、作用域与闭包(第七篇)---关于闭包典型例子的理解
- [Mysql必知必会系列]数据过滤·IN和NOT操作符
- i++在两个线程执行100次,最终的结果是
- 第一次作业答案(官方)
- 腾讯云开发者实验室——深度学习破解验证码