- 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 算法
下次再看
本文探讨了如何使用递归及Morris算法求解二叉树中所有叶节点的和,提供了一种O(1)空间复杂度的高效解决方案。
532

被折叠的 条评论
为什么被折叠?



