# Code language: Python classSolution: deffindBottomLeftValue(self, root: Optional[TreeNode]) -> int: ans, h = 0, 0
defdfs(root, height): if root: nonlocal ans, h if height > h: ans, h = root.val, height if root.left: dfs(root.left, height + 1) if root.right: dfs(root.right, height + 1) dfs(root, 1) return ans
publicvoiddfs(TreeNode root, int height) { if (root != null) { if (height > h) { h = height; val = root.val; } dfs(root.left, height + 1); dfs(root.right, height + 1); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Code language: C++ classSolution { public: intfindBottomLeftValue(TreeNode* root){ int ans = 0, h = 0; function<void(TreeNode*, int)> dfs = [&ans, &h, &dfs](TreeNode* root, int height) { if (root != nullptr) { if (h < height) { ans = root->val; h = height; } if (root->left != nullptr) dfs(root->left, height + 1); if (root->right != nullptr) dfs(root->right, height + 1); } }; dfs(root, 1); return ans; } };
BFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Code language: Python classSolution: deffindBottomLeftValue(self, root: Optional[TreeNode]) -> int: ans = 0 st = collections.deque([root]) while st: ans = st[0].val # 注意这里 len(st) 只在创建 range 迭代器的时候进行唯一一次传参 # 循环中不会传参也不会更新 range 迭代器的终点值 for _ inrange(len(st)): cur = st.popleft() if cur.left: st.append(cur.left) if cur.right: st.append(cur.right) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Code language: Java classSolution { publicintfindBottomLeftValue(TreeNode root) { Deque<TreeNode> st = newArrayDeque<>(); if (root != null) st.add(root); intans=0; while (!st.isEmpty()) { ans = st.peekFirst().val; for (inti=0, n = st.size(); i < n; ++i) { TreeNodecur= st.pollFirst(); if (cur.left != null) st.addLast(cur.left); if (cur.right != null) st.addLast(cur.right); } } return ans; } }
// Code language: C++ classSolution { public: intfindBottomLeftValue(TreeNode* root){ queue<TreeNode*> st; if (root != nullptr) st.push(root); int ans = 0; while (!st.empty()) { ans = st.front()->val; for (int i = 0, n = st.size(); i < n; ++i) { TreeNode* cur = st.front(); st.pop(); if (cur->left != nullptr) st.push(cur->left); if (cur->right != nullptr) st.push(cur->right); } } return ans; } };