leetcode题解-105-从前序与中序遍历序列构造二叉树

题目

当当喵 way

dfs遍历 + isLeft来标注当前节点状态即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int sum = 0;
void getSum(TreeNode* root, bool isLeft)
{
if (!root) return;

if (isLeft && !root->left && !root->right)
{
sum += root->val;
}
else
{
getSum(root->left, true);
getSum(root->right, false);
}
}
public:
int sumOfLeftLeaves(TreeNode* root)
{
getSum(root, false);

return sum;
}
};

References

https://leetcode-cn.com/problems/sum-of-left-leaves/solution/chao-ji-rong-yi-li-jie-qi-shi-he-qiu-quan-lu-jing-/