https://leetcode.com/problems/sum-of-left-leaves/description/
Solution 1. Recursive tree traversal, use a bool to indicate if the node is the left branch.
void inOrder(TreeNode*node, int &s, bool left) {
if(!node) return;
if(node->left) inOrder(node->left, s, true);
if(left && !node->left && !node->right) s += node->val;
if(node->right) inOrder(node->right, s, false);
}
int sumOfLeftLeaves(TreeNode* root) {
int s=0;
inOrder(root, s, false);
return s;
}
Solution 2. Iterative tree traversal.
int sumOfLeftLeaves(TreeNode* root) {
if(!root) return 0;
int s=0;
bool isLeft = false;
TreeNode* node = root;
stack<TreeNode*> st;
st.push(node);
while(!st.empty()){
node = st.top();
st.pop();
if(isLeft && !node->left && !node->right) {
s += node->val;
isLeft = false;
continue;
}
if(node->right) {
st.push(node->right);
isLeft = false;
}
if(node->left) {
st.push(node->left);
isLeft = true;
}
}
return s;
}
No comments:
Post a Comment