File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .gatsby ;
2+
3+ import java .util .Objects ;
4+
5+ /**
6+ * @ClassName: _222CountCompleteTreeNodes
7+ * @Description: leetcode 222 完全二叉树的节点数量
8+ * @author: Gatsby
9+ * @date: 2022/7/29 10:48
10+ */
11+
12+ public class _222CountCompleteTreeNodes {
13+ /**
14+ * @MethodName: countNodes
15+ * @Parameter: [root]
16+ * @Return int
17+ * @Description: 递归
18+ * @author: Gatsby
19+ * @date: 2022/7/29 10:50
20+ */
21+ public int countNodes (TreeNode root ) {
22+ if (Objects .isNull (root )) {
23+ return 0 ;
24+ } else return countNodes (root .left ) + countNodes (root .right ) + 1 ;
25+ }
26+
27+ /**
28+ * @MethodName: countNodesBs
29+ * @Parameter: [root]
30+ * @Return int
31+ * @Description: 二分查找
32+ * @author: Gatsby
33+ * @date: 2022/7/29 10:58
34+ */
35+ public int countNodesBs (TreeNode root ) {
36+ if (Objects .isNull (root )) return 0 ;
37+ int left = countHeight (root .left );
38+ int right = countHeight (root .right );
39+
40+ // 如果左子树和右子树的深度相等,那么左子树一定是个满二叉树,加上一个root节点
41+ // 直接用1 << left计算就行
42+ if (left == right ) {
43+ return countNodesBs (root .right ) + (1 << left );
44+ }
45+ return countNodesBs (root .left ) + (1 << right );
46+ }
47+
48+ private int countHeight (TreeNode root ) {
49+ int height = 0 ;
50+ while (!Objects .isNull (root )) {
51+ height ++;
52+ root = root .left ;
53+ }
54+ return height ;
55+ }
56+ }
57+
58+
You can’t perform that action at this time.
0 commit comments