(C ++) (Binary Tree) LetCode # 222. Count Complete Tree Nodes

  • Question: Calculate the number of nodes in a complete binary tree
  • Difficulty: Medium
  • Idea: According to the definition of a complete binary tree, only the bottom layer of the tree may not be full, and the rest of the layers are full. Therefore, it is necessary to know the height of the binary tree and the number of nodes at the bottom layer; the number of nodes at the bottom layer can be determined by "judging the left Whether the subtree has the rightmost child" is calculated. If the left subtree has the rightmost child, the right subtree may also have the bottommost child.
  • Code:
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        int count = 0, height = 0;
        TreeNode* tmp = root;
        while (tmp != NULL) {
            height++;
            tmp = tmp->left;
        }
        int level = height - 2;
        tmp = root;
        while (level >= 0) {
            TreeNode* left = tmp->left;
            //找到左孩子的最右子节点
            for (int i = 0; i < level; i++){
                left = left->right;
            }
            //如果左子树存在最右结点,则需要判断右子树是否存在最底层结点
            if (left) {
                tmp = tmp->right;
                count += (1 << level);
            } else {
                tmp = tmp->left;
            }
            level--;
        }
        if (tmp) count++;
        return count + (1 << height-1) -1;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325606625&siteId=291194637