[Leetcode 222, Medium] Count Complete Tree Nodes

来源:互联网 发布:网站设计优化 编辑:程序博客网 时间:2024/05/18 09:07

Problem:

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Analysis:


Solutions:

C++:

    int countNodes(TreeNode* root) {    if (root == NULL)    return 0;    stack<TreeNode *> node_stack;    TreeNode *p_cur = root;    TreeNode *p_visited = NULL;    int height = 0;    int longer_path_num = 0;    while (p_cur || !node_stack.empty()) {    if (p_cur) {    node_stack.push(p_cur);    p_cur = p_cur->left;    } else {    if (height == 0) {    height = node_stack.size();    ++longer_path_num;    }    else if (height == node_stack.size())    ++longer_path_num;    p_cur = node_stack.top();    if (height > node_stack.size() && p_cur->right == NULL)    break;    if (p_cur->right == NULL || p_cur->right == p_visited) {    node_stack.pop();    p_visited = p_cur;    p_cur = NULL;    } else    p_cur = p_cur->right;    }    }    return static_cast<int>(pow(2, height - 1)) - 1 + longer_path_num;    }
Java:


Python:

0 0