[leetcode]222. Count Complete Tree Nodes

来源:互联网 发布:win10系统重装软件 编辑:程序博客网 时间:2024/05/17 20:33

题目地址

https://leetcode.com/problems/count-complete-tree-nodes/

题目大意

求一个完全二叉树的节点数量

解题思路

最简单的是遍历数节点,复杂度O(n),不出意外的TLE了。考虑到时完全二叉树,所以可以通过比较最左叶子节点,和最右叶子节点的高度,来判断是不是满二叉树,如果是满二叉树,则直接能求出节点个数。如果不是则分别对左右子树做此递归操作。时间复杂度是O(h^2),可以AC。

代码

class Solution {public:    int countNodes(TreeNode* root) {        if (root == NULL) {            return 0;        }        int l = leftHigh(root);        int r = rightHigh(root);        if (l == r) {            return (2 << (l - 1)) - 1;        } else {            return countNodes(root->left) + countNodes(root->right) + 1;        }    }private:    int leftHigh(TreeNode * root) {        int h = 0;        while (root != NULL) {            root = root->left;            ++h;        }        return h;    }    int rightHigh(TreeNode * root) {        int h = 0;        while (root != NULL) {            root = root->right;            ++h;        }        return h;    }};
0 0
原创粉丝点击