222. Count Complete Tree Nodes - Medium
Given a?complete?binary tree,count the number of nodes. Note: Definition of a complete binary tree from?Wikipedia: Example: Input: 1 / 2 3 / / 4 5 6 Output: 6 ? 思路:比较左右子树深度是否相等,如果相等,返回2 ^ h - 1;不等则对左右子节点递归。因为是complete tree,求左右子树的深度只要一直往左/右走并计数即可 time: O(logn * logn),space: O(n) worst case,O(logn) best case /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int countNodes(TreeNode root) { if(root == null) { return 0; } int leftDepth = depth(root,true); int rightDepth = depth(root,false); if(leftDepth == rightDepth) { return (1 << leftDepth) - 1; } else { return 1 + countNodes(root.left) + countNodes(root.right); } } public int depth(TreeNode node,boolean isLeft) { int depth = 0; while(node != null) { node = isLeft ? node.left : node.right; depth++; } return depth; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |