欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

222. Count Complete Tree Nodes

发布时间:2025/3/18 编程问答 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 222. Count Complete Tree Nodes 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目:
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.

解答:

public class Solution {//学了enum的方法哈哈public enum Direction {LEFT, RIGHT}public int getDepth(TreeNode root, Direction dir) {int depth = 0;//这里是从root开始算起,所以求出来的结果是实际depth + 1while (root != null) {depth++;if (dir == Direction.LEFT) {root = root.left;} else {root = root.right;}}return depth;}public int countNodes(TreeNode root) {if (root == null) return 0;int leftDepth = getDepth(root, Direction.LEFT);int rightDepth = getDepth(root, Direction.RIGHT);if (leftDepth == rightDepth) {//1 << leftDepth是2^(leftDepth)return (1 << leftDepth) - 1;} else {//这一步很巧妙,把根结点加上,然后分治左结点和右结点,如果是叶子结点,在countNodes中就返回1return 1 + countNodes(root.left) + countNodes(root.right);}} }

总结

以上是生活随笔为你收集整理的222. Count Complete Tree Nodes的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。