程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 222. Count Complete Tree Nodes,completenodes

222. Count Complete Tree Nodes,completenodes

編輯:JAVA綜合教程

222. Count Complete Tree Nodes,completenodes


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.

代碼如下:(超時)

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int countNodes(TreeNode root) {
12         List<TreeNode> list=PreOrder(root);
13         return list.size();
14         
15     }
16     public List<TreeNode> PreOrder(TreeNode root){
17         List<TreeNode> list=new ArrayList<>();
18         if(root==null)
19         return list;
20         
21         list.add(root);
22         if(root.left!=null)
23         list.addAll(PreOrder(root.left));
24         if(root.right!=null)
25         list.addAll(PreOrder(root.right));
26         return list;
27     }
28 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved