LeetCode June Challenge - Day 23

Problem: LeetCode June Challenge - Day 23

Ideas

  1. Use a stack instead of recursion for better performance.

Solution:

class Solution {
    public:
        int countNodes(TreeNode* root) {
            if(root == NULL) return 0;
            int ans = 0;
            stack<TreeNode*> s;
            s.push(root);
            while(!s.empty()){
                root = s.top();
                s.pop();
                ans++;
                if(root->left != NULL) s.push(root->left);
                if(root->right != NULL) s.push(root->right);
            }
            return ans;
        }
};