【LeetCode】312. Burst Balloons

来源:互联网 发布:易语言天龙八部源码 编辑:程序博客网 时间:2024/05/18 04:17

题目:

You need to find the largest value in each row of a binary tree.

Example:

Input:           1         / \        3   2       / \   \        5   3   9 Output: [1, 3, 9]

题解:因为这道题是在DFS下的,所以首先想到用DFS做。递归调用分别对左右子树进行操作,每一行的第一个数字最先放入result,剩下的数字与result里这一行的数字进行比较,留下最大值。最好按照题目给出的例子,模拟一遍调用过程,这样就能看出来进行比较时,是对result[row-1]的数字进行比较,而不是result[row]。一开始递归调用时我写的是row++,run code时your answer一直是空的,于是我输出每次的row和result的内容来debug,发现row并没有增加,依然是1,换成++row,发现输出结果十分奇怪。最终我改成row+1,终于对了!得到教训,能用n+1的地方不要用n++或者++n,这两个式子十分不稳定。


答案:DFS


class Solution {
public:
void f(TreeNode* root,int row,vector<int> &result)
{
if(root==NULL)
return;
if(row>result.size())
result.push_back(root->val);
else
result[row-1]=max(result[row-1],root->val);
f(root->left,row+1,result);
f(root->right,row+1,result);
}
vector<int> largestValues(TreeNode* root) 
{
    vector<int> result;
int row=1;
f(root,row,result);
return result;
}
};


Solution里面的BFS这里也贴出来:

class Solution {public:    vector<int> largestValues(TreeNode* root) {        vector<int> res;        queue<TreeNode*> q;        if (root) q.push(root);        int curr = q.size();        while (curr) {            res.emplace_back(INT_MIN);            while (curr--) {                res.back() = max(res.back(), q.front()->val);                if (q.front()->left)  q.push(q.front()->left);                if (q.front()->right) q.push(q.front()->right);                q.pop();            }            curr = q.size();        }                return res;    }};

0 0
原创粉丝点击