classSolution { publicintfindBottomLeftValue(TreeNode root) { Deque<TreeNode> d = newArrayDeque<>(); d.addLast(root); intans=0; while (!d.isEmpty()) { intsz= d.size(); ans = d.peek().val; while (sz-- > 0) { TreeNodepoll= d.pollFirst(); if (poll.left != null) d.addLast(poll.left); if (poll.right != null) d.addLast(poll.right); } } return ans; } }
C++ 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intfindBottomLeftValue(TreeNode* root){ deque<TreeNode*> d; d.push_back(root); int ans = 0; while (!d.empty()) { int sz = d.size(); ans = d.front()->val; while (sz-- > 0) { TreeNode* poll = d.front(); d.pop_front(); if (poll->left != nullptr) d.push_back(poll->left); if (poll->right != nullptr) d.push_back(poll->right); } } return ans; } };
Python 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: deffindBottomLeftValue(self, root: Optional[TreeNode]) -> int: d = deque([root]) ans = 0 while d: sz = len(d) ans = d[0].val while sz > 0: poll = d.popleft() if poll.left: d.append(poll.left) if poll.right: d.append(poll.right) sz -= 1 return ans
TypeScript 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functionfindBottomLeftValue(root: TreeNode | null): number { const d = [root]; let ans = 0; while (d.length > 0) { const sz = d.length; ans = d[0].val; for (let i = 0; i < sz; i++) { const poll = d.shift()!; if (poll.left) d.push(poll.left); if (poll.right) d.push(poll.right); } } return ans; };