File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -243,6 +243,74 @@ Python:
243
243
244
244
Go:
245
245
246
+ JavaScript:
247
+
248
+ 递归版本
249
+ ``` javascript
250
+ var countNodes = function (root ) {
251
+ // 递归法计算二叉树节点数
252
+ // 1. 确定递归函数参数
253
+ const getNodeSum = function (node ){
254
+ // 2. 确定终止条件
255
+ if (node=== null ){
256
+ return 0 ;
257
+ }
258
+ // 3. 确定单层递归逻辑
259
+ let leftNum= getNodeSum (node .left );
260
+ let rightNum= getNodeSum (node .right );
261
+ return leftNum+ rightNum+ 1 ;
262
+ }
263
+ return getNodeSum (root);
264
+ };
265
+ ```
266
+
267
+ 迭代(层序遍历)版本
268
+ ``` javascript
269
+ var countNodes = function (root ) {
270
+ // 层序遍历
271
+ let queue= [];
272
+ if (root=== null ){
273
+ return 0 ;
274
+ }
275
+ queue .push (root);
276
+ let nodeNums= 0 ;
277
+ while (queue .length ){
278
+ let length= queue .length ;
279
+ while (length-- ){
280
+ let node= queue .shift ();
281
+ nodeNums++ ;
282
+ node .left && queue .push (node .left );
283
+ node .right && queue .push (node .right );
284
+ }
285
+ }
286
+ return nodeNums;
287
+ };
288
+ ```
289
+
290
+ 利用完全二叉树性质
291
+ ``` javascript
292
+ var countNodes = function (root ) {
293
+ // 利用完全二叉树的特点
294
+ if (root=== null ){
295
+ return 0 ;
296
+ }
297
+ let left= root .left ;
298
+ let right= root .right ;
299
+ let leftHeight= 0 ,rightHeight= 0 ;
300
+ while (left){
301
+ left= left .left ;
302
+ leftHeight++ ;
303
+ }
304
+ while (right){
305
+ right= right .right ;
306
+ rightHeight++ ;
307
+ }
308
+ if (leftHeight== rightHeight){
309
+ return Math .pow (2 ,leftHeight+ 1 )- 1 ;
310
+ }
311
+ return countNodes (root .left )+ countNodes (root .right )+ 1 ;
312
+ };
313
+ ```
246
314
247
315
248
316
You can’t perform that action at this time.
0 commit comments