publicvoiddfs(TreeNode root, int h, List<Integer> ans) { if (root != null) { if (h >= ans.size()) ans.add(root.val); else ans.set(h, Math.max(ans.get(h), root.val)); dfs(root.left, h + 1, ans); dfs(root.right, h + 1, ans); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: C++ classSolution { public: vector<int> largestValues(TreeNode* root){ vector<int> ans; function<void(TreeNode*, int)> dfs = [&ans, &dfs](TreeNode* root, int h) { if (root != nullptr) { if (h >= ans.size()) ans.emplace_back(root->val); else ans[h] = max(ans[h], root->val); dfs(root->left, h + 1); dfs(root->right, h + 1); } }; dfs(root, 0); return ans; } };
时间复杂度: \(O(n)\), \(n\) 表示二叉树结点数量
空间复杂度: \(O(n)\)
广度优先搜索
分层 BFS,记录每层最大值即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Code language: Python classSolution: deflargestValues(self, root: Optional[TreeNode]) -> List[int]: st = deque() ans = list() if root: st.append(root) while st: ans.append(max(node.val for node in st)) for _ inrange(len(st)): cur = st.popleft() if cur.left: st.append(cur.left) if cur.right: st.append(cur.right) return ans
// Code language: C++ classSolution { public: vector<int> largestValues(TreeNode* root){ queue<TreeNode*> st; vector<int> ans; if (root != nullptr) st.push(root);
while (!st.empty()) { int val = st.front()->val; for (int i = 0, n = st.size(); i < n; ++i) { TreeNode* cur = st.front(); st.pop(); val = max(val, cur->val); if (cur->left != nullptr) st.push(cur->left); if (cur->right != nullptr) st.push(cur->right); } ans.push_back(val); } return ans; } };