1. 程式人生 > >[LeetCode]515. Find Largest Value in Each Tree Row

[LeetCode]515. Find Largest Value in Each Tree Row

[LeetCode]515. Find Largest Value in Each Tree Row

題目描述

這裡寫圖片描述

思路

遞迴,深度優先
使用陣列儲存對應層的最大值

程式碼

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class
Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> res; if (root == NULL) return res; res.push_back(root->val); travel(root, 0, res); return res; } private: void travel(TreeNode* root, int level, vector<int
>
& res) { if (root == NULL) return; if (level < res.size()) res[level] = max(res[level], root->val); else res.push_back(root->val); travel(root->left, level + 1, res); travel(root->right, level + 1, res); } }; int main() { TreeNode* t1 = new
TreeNode(1); TreeNode* t2 = new TreeNode(3); TreeNode* t3 = new TreeNode(2); TreeNode* t4 = new TreeNode(5); TreeNode* t5 = new TreeNode(3); TreeNode* t6 = new TreeNode(9); t1->left = t2; t1->right = t3; t2->left = t4; t2->right = t5; t3->right = t6; Solution s; vector<int> res = s.largestValues(t1); for (int num : res) cout << num << " "; cout << endl; system("pause"); return 0; }