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.
先找到从root出发到最左和最右的距离, 如果距离相等说明最后一行自左到右都有node 总共2^n - 1个
如果不相等, 递归的找出左右不同的敌方和个数
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.
先找到从root出发到最左和最右的距离, 如果距离相等说明最后一行自左到右都有node 总共2^n - 1个
如果不相等, 递归的找出左右不同的敌方和个数
public class Solution { public int countNodes(TreeNode root) { if (root == null) { return 0; } int left = findleft(root); int right = findright(root); if (left == right) { return (2<<left - 1) - 1;//减号优先等级大于<< } else { return countNodes(root.left) + countNodes(root.right) + 1; } } public int findleft(TreeNode root) { int res = 0; while (root != null) { root = root.left; res++; } return res; } public int findright(TreeNode root) { int res = 0; while (root != null) { root = root.right; res++; } return res; } }
没有评论:
发表评论