LeetCode 每日一題 2021-4-27 (二叉搜尋樹的範圍和)
阿新 • • 發佈:2021-04-28
難度簡單
給定二叉搜尋樹的根結點root
,返回值位於範圍[low, high]
之間的所有結點的值的和。
示例 1:
輸入:root = [10,5,15,3,7,null,18], low = 7, high = 15 輸出:32
思路一:遞迴+剪枝:
通過遞迴搜尋方式遍歷各節點:
① 若當前節點為空,返回 0;
② 若當前節點大於最大值,返回左子樹的和;
③ 若當前節點小於最小值,返回右子樹的和;
④ 返回已當前結點為根節點的樹的和。
程式碼:
// 遞迴實現 + 剪枝 int rangeSumBST(TreeNode* root, int low, int high) { if(root==nullptr) return 0; if(root->val > high) return rangeSumBST(root->left, low, high); if(root->val < low) return rangeSumBST(root->right, low, high); return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); }
思路二:迭代:
遍歷全部的節點,節點滿足條件的加入結果中
程式碼:
// 迭代實現 int rangeSumBST(TreeNode* root, int low, int high) { stack<TreeNode*> data; TreeNode* cur; data.push(root); int ans=0; while(!data.empty()){ cur = data.top(); data.pop(); if(cur){ if(cur->right) data.push(cur->right); if(cur->left) data.push(cur->left); data.push(cur); data.push(nullptr); }else{ if(data.top()->val >= low && data.top()->val <= high ) ans+=data.top()->val; data.pop(); } } return ans; }
思路二:迭代 + 剪枝:
通過迭代搜尋方式遍歷各節點:
① 若當前節點為空,繼續迴圈;
② 若當前節點大於最大值,壓入左節點;
③ 若當前節點小於最小值,壓入右節點;
④ 將該節點值加入結果中,並壓入子節點。
程式碼:
// 迭代+剪枝 int rangeSumBST(TreeNode *root, int low, int high) { int sum = 0; queue<TreeNode*> q({root}); while (!q.empty()) { auto node = q.front(); q.pop(); if (node == nullptr) { continue; } if (node->val > high) { q.push(node->left); } else if (node->val < low) { q.push(node->right); } else { sum += node->val; q.push(node->left); q.push(node->right); } } return sum; }