Count Complete Tree Nodes

原创 2015年07月08日 10:24:24
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = leftHeight(root);
        int right = rightHeight(root);
        if (left == right) {
            return (2<<left) - 1;
        } else {
            return countNodes(root.left) + countNodes(root.right) + 1;
        }
    }
    private int leftHeight(TreeNode node) {
        TreeNode left = node.left;
        int height = 0;
        while (left != null) {
            left = left.left;
            height++;
        }
        return height;
    }
    private int rightHeight(TreeNode node) {
        TreeNode right = node.right;
        int height = 0;
        while (right != null) {
            right = right.right;
            height++;
        }
        return height;
    }
}

相关文章推荐

算法分析与设计课程(12):【leetcode】 Count Complete Tree Nodes

Description: Given a complete binary tree, count the number of nodes. Definition of a complete b...

leetcode -- 222. Count Complete Tree Nodes【子问题划分】

题目 Given a complete binary tree, count the number of nodes. Definition of a complete binary tree fr...

leetcode - Count Complete Tree Nodes

题目: Count Complete Tree Nodes   Given a complete binary tree, count the number of nodes...

leetCode(19):Count Complete Tree Nodes

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

Binary search (4) -- Find Right Interval,Count Complete Tree Nodes,Divide Two Integers

Find Right Interval,Count Complete Tree Nodes,Divide Two Integers
  • dwt0317
  • dwt0317
  • 2017年01月18日 15:12
  • 109

LeetCode 222. Count Complete Tree Nodes 题解——Java

题目链接:https://leetcode.com/problems/count-complete-tree-nodes/#/description 题目要求:计算完全二叉树的节点个数 思...

LeetCode——Count Complete Tree Nodes

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left...

leetcode--Count Complete Tree Nodes

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

(未完成!)Leetcode 222. Count Complete Tree Nodes

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

leetcode222---Count Complete Tree Nodes(求完全二叉树节点数)

问题描述:Given a complete binary tree, count the number of nodes.In a complete binary tree every level, ...
  • will130
  • will130
  • 2016年01月22日 22:28
  • 223
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Count Complete Tree Nodes
举报原因:
原因补充:

(最多只允许输入30个字)