- Sum of leaf nodes
Given a binary tree, find the sum of all leaf nodes.Use O(1) space.
Example
Given binary tree:
1
/
2 3
/ \
4 5
Return : 12
Notice
1.参考Morris 算法
解法1:最基本的递归
/**
* 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:
* @return: the sum of leafnode
*/
int sumLeafNode(TreeNode * root) {
if (!root) return 0;
if (!root->left && !root->right) return root->val;
return sumLeafNode(root->left) + sumLeafNode(root->right);
}
};
解法2. Morris 算法
下次再看