【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