Help for some more faster mothods. Thx.


  • 0
    W

    My algorithm based on level order traversal using a queue works in 48ms. Can some one share me some ideas that run more faster? Here is my solution:

    int minDepth(TreeNode *root){
    	if (root == NULL){
    		return 0;
    	}
    	queue<TreeNode *> nodeQueue;
    	nodeQueue.push(root);
    	int depth = 1;
    	while (!nodeQueue.empty()){
    		int levelNum = nodeQueue.size();
    		for (int idx = 1;idx <= levelNum;++idx){
    			TreeNode *ptr = nodeQueue.front();
    			nodeQueue.pop();
    			if (ptr->left == NULL && ptr->right == NULL){
    				// Leaf node
    				return depth;
    			}
    			if (ptr->left != NULL){
    				nodeQueue.push(ptr->left);
    			}
    			if (ptr->right != NULL){
    				nodeQueue.push(ptr->right);
    			}
    		}
    		++depth;
    	}
    	return depth;
    }
    

    Any comment will be appreciated.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.