当前位置:网站首页>Leetcode-404:左叶子之和
Leetcode-404:左叶子之和
2022-07-03 09:22:00 【ITSOK_U】
404. 左叶子之和
题目描述:
给定二叉树的根节点 root ,返回所有左叶子之和。
深度优先(O(N),O(N))
class Solution {
public:
void getLeftNum(TreeNode* root, int &n){
// 根节点为空或者只有一个节点则返回
if(!root->left && !root->right || root == nullptr ) return;
// 该节点有左叶子就加和
else if(root->left != nullptr && root->left->left == nullptr && root->left->right==nullptr) n+=root->left->val;
//否则继续处理左子树
else if(root->left)
getLeftNum(root->left,n);
// 处理右子树
if(root->right)
getLeftNum(root->right,n);
}
int sumOfLeftLeaves(TreeNode* root) {
int n =0 ;
getLeftNum(root,n);
return n;
}
};
广度优先(O(N),O(N))
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root->left && !root->right || root==nullptr) return 0;
// 初始化返回值
int res=0;
// 广度优先遍历
queue<TreeNode*> que;
que.push(root);
// 广度优先遍历处理模板
while(!que.empty()){
TreeNode* node = que.front();
que.pop();
// 左孩子入队
if(node->left){
que.push(node->left) ;
// 如果左孩子是叶子节点就加和
if(node->left->left == nullptr && node->left->right == nullptr)
res+=node->left->val;
}
// 右孩子入队
if(node->right) que.push(node->right);
}
return res;
}
};
边栏推荐
- Opencv note 21 frequency domain filtering
- LeetCode - 508. Sum of subtree elements with the most occurrences (traversal of binary tree)
- CV learning notes ransca & image similarity comparison hash
- 4G module IMEI of charging pile design
- I think all friends should know that the basic law of learning is: from easy to difficult
- Opencv Harris corner detection
- openCV+dlib實現給蒙娜麗莎換臉
- The data read by pandas is saved to the MySQL database
- 20220610其他:任务调度器
- The underlying principle of vector
猜你喜欢
LeetCode - 706 设计哈希映射(设计) *
LeetCode - 900. RLE 迭代器
Retinaface: single stage dense face localization in the wild
SCM is now overwhelming, a wide variety, so that developers are overwhelmed
CV learning notes convolutional neural network
pycharm 无法引入自定义包
Basic use and actual combat sharing of crash tool
Development of intelligent charging pile (I): overview of the overall design of the system
Leetcode-112:路径总和
2312、卖木头块 | 面试官与狂徒张三的那些事(leetcode,附思维导图 + 全部解法)
随机推荐
My 4G smart charging pile gateway design and development related articles
Do you understand automatic packing and unpacking? What is the principle?
About windows and layout
LeetCode - 919. Full binary tree inserter (array)
Yocto Technology Sharing Phase 4: Custom add package support
Octave instructions
CV learning notes ransca & image similarity comparison hash
Application of external interrupts
Working mode of 80C51 Serial Port
Leetcode-112:路径总和
Sending and interrupt receiving of STM32 serial port
Pymssql controls SQL for Chinese queries
Problems encountered when MySQL saves CSV files
Simulate mouse click
Serial port programming
使用sed替换文件夹下文件
openEuler kernel 技術分享 - 第1期 - kdump 基本原理、使用及案例介紹
It is difficult to quantify the extent to which a single-chip computer can find a job
Leetcode 300 最长上升子序列
20220604数学:x的平方根