# Code language: Python classSolution: defsumRootToLeaf(self, root: Optional[TreeNode]) -> int: ans = 0 defdfs(root, r): if root: val = (r << 1) + root.val if root.left: dfs(root.left, val) if root.right: dfs(root.right, val) ifnot root.left andnot root.right: nonlocal ans ans += val dfs(root, 0) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: Cpp classSolution { public: intsumRootToLeaf(TreeNode *root){ int ans = 0; function<void(TreeNode *, int)> dfs = [&](TreeNode *root, int r) { int val = (r << 1) + root->val; if (root->left != nullptr) dfs(root->left, val); if (root->right != nullptr) dfs(root->right, val); if (root->left == nullptr && root->right == nullptr) ans += val; return val; }; if (root != nullptr) dfs(root, 0); return ans; } };
publicvoiddfs(TreeNode root, int r) { intval= (r << 1) + root.val; if (root.left != null) dfs(root.left, val); if (root.right != null) dfs(root.right, val); if (root.left == null && root.right == null) ans += val; } }
不使用全局变量,通过函数返回值返回结果的写法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Code language: Python classSolution: defsumRootToLeaf(self, root: Optional[TreeNode]) -> int: defdfs(root, r): ans = 0 if root: val = (r << 1) + root.val if root.left: ans += dfs(root.left, val) if root.right: ans += dfs(root.right, val) ifnot root.left andnot root.right: ans += val return ans return dfs(root, 0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Code language: Cpp classSolution { public: intsumRootToLeaf(TreeNode *root){ function<int(TreeNode *, int)> dfs = [&dfs](TreeNode *root, int r) { int val = (r << 1) + root->val, ans = 0; if (root->left != nullptr) ans += dfs(root->left, val); if (root->right != nullptr) ans += dfs(root->right, val); if (root->left == nullptr && root->right == nullptr) ans += val; return ans; }; return root == nullptr ? 0 : dfs(root, 0); } };
# 栈中存(结点,父节点代表的二进制数) st = list() if root: st.append((root, 0)) while st: cur, val = st.pop() val = (val << 1) + cur.val ifnot cur.left andnot cur.right: ans += val if cur.right: st.append((cur.right, val)) if cur.left: st.append((cur.left, val)) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Code language: Cpp classSolution { public: intsumRootToLeaf(TreeNode *root){ int ans; stack<pair<TreeNode *, int>> st; if (root != nullptr) st.emplace(pair{root, 0}); while (!st.empty()) { auto &p = st.top(); TreeNode *cur = p.first; int val = (p.second << 1) + cur->val; st.pop(); if (cur->right != nullptr) st.emplace(pair{cur->right, val}); if (cur->left != nullptr) st.emplace(pair{cur->left, val}); if (cur->left == nullptr && cur->right == nullptr) ans += val; } return ans; } };