当前位置:网站首页>Leetcode 222 number of nodes of complete binary tree

Leetcode 222 number of nodes of complete binary tree

2022-07-05 04:32:00 baj001

Ideas

Original link

  1. Method 1 : Using recursion , as follows
  2. Method 2 : Use the classic solution , Sequence traversal , To count the number of nodes
class Solution {
    
    //  General recursive solution 
    public int countNodes(TreeNode root) {
    
        if(root == null) {
    
            return 0;
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}

	// Use iterative algorithm 
class Solution {
    
    public int countNodes(TreeNode root) {
    
        if(root == null) return 0;
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        que.add(root);
        int num = 0;
        while(!que.isEmpty()){
    
            int size = que.size();
            while(size > 0){
    
                TreeNode node = que.poll();
                if(node.left != null) que.add(node.left);
                if(node.right != null) que.add(node.right);
                num++;
                size--;
            }
        }
        return num;
    }
}
原网站

版权声明
本文为[baj001]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140636587226.html