给定一棵完全二叉树的头节点head,返回这棵树的节点个数。
完全二叉树指:设二叉树的深度为h,则 [1,h-1] 层的节点数都满足 个
数据范围:节点数量满足 ,节点上每个值都满足
进阶:空间复杂度 , 时间复杂度
class Solution { public: int nodeNum(struct TreeNode* head) { if (!head) return 0; return 1 + nodeNum(head->left) + nodeNum(head->right); } };
/** struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: int get_height(struct TreeNode *head){ return head == NULL ? 0 : get_height(head->left) + 1; } int nodeNum(struct TreeNode* head) { if(head == NULL) return 0; int height = get_height(head); int cur_h = 1; if(head->right != NULL){ struct TreeNode *new_head = head->right; cur_h++; while(new_head->left != NULL){ new_head = new_head->left; cur_h++; } } if(cur_h == height) return pow(2, height-1) + nodeNum(head->right); else return pow(2, cur_h-1) + nodeNum(head->left); } };
public class Solution { int nodeCount = 0; public int nodeNum(TreeNode head) { count(head); return nodeCount; } public void count(TreeNode root) { if(root != null){ nodeCount ++; count(root.left); count(root.right); } } }但其实我们有更好的方法来进行优化,假设整棵树的深度为h(只要溜一遍树的左边界就可以得到),我们每次考虑右树最左的节点有没有到整棵树的最深层。
public class Solution { public int nodeNum(TreeNode head) { if(head == null) return 0; // 空树返回0 return bs(head, 1, mostLeftLevel(head, 1)); } // 计算node为根的子树最深可以到达哪一层,level为node节点所在层号 private int mostLeftLevel(TreeNode node, int level) { while(node != null){ level ++; node = node.left; } return level - 1; } // node在第level层,h为树深 private int bs(TreeNode node, int level, int h){ if(level == h) return 1; if(mostLeftLevel(node.right, level + 1) == h){ // 右树的最左节点到底了,左树一定是满二叉树,右树递归 return (1 << (h - level)) + bs(node.right, level + 1, h); }else{ // 右树的最左节点没到底,右树一定是满二叉树,左树递归 return (1 << (h - level - 1)) + bs(node.left, level + 1, h); } } }
public int nodeNum(TreeNode head) { if(head == null) return 0; int leftCnt = nodeNum(head.left) + 1; int rightCnt = nodeNum(head.right) + leftCnt; return rightCnt; }
public static int getHeight(TreeNode head) { return head == null ? 0 : getHeight(head.left) + 1; } public static int nodeNum(TreeNode head) { if (head == null) return 0; // 求出高度 int height = getHeight(head); int curHeight = 1; if (head.right != null) { TreeNode newHead = head.right; curHeight++; while (newHead.left != null) { newHead = newHead.left; curHeight++; } } if (curHeight == height) // 说明当前的 head 左边是满的,则不满的在右边 return (int) Math.pow(2, height - 1) + nodeNum(head.right); else // 高度不一致,则说明右边是满的,则说明不满的在左边 return (int) Math.pow(2, curHeight - 1) + nodeNum(head.left); }
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <queue> class Solution { public: /** 层序遍历,一边遍历一边计数 */ int nodeNum(TreeNode* head) { int ans = 0; queue<TreeNode*>lab; lab.push(head); while (!lab.empty()) { TreeNode* temp = lab.front(); lab.pop(); if (temp) { ans++; lab.push(temp->left); lab.push(temp->right); } } return ans; } };
public int nodeNum (TreeNode head) { // write code here int res=0; LinkedList<TreeNode> queue=new LinkedList<>(); queue.add(head); while(!queue.isEmpty()){ TreeNode node=queue.poll(); if(node==null){ return res; }else{ res++; queue.add(node.left); queue.add(node.right); } } return res; }
if not head: return 0 return self.nodeNum(head.left)+1+self.nodeNum(head.right) #递归
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct TreeNode { * pub val: i32, * pub left: Option<Box<TreeNode>>, * pub right: Option<Box<TreeNode>>, * } * * impl TreeNode { * #[inline] * fn new(val: i32) -> Self { * TreeNode { * val: val, * left: None, * right: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head TreeNode类 * @return int整型 */ pub fn nodeNum(&self, mut head: Option<Box<TreeNode>>) -> i32 { // write code here if head.is_none() {0} else { 1 + self.nodeNum(head.as_mut().unwrap().left.take()) + self.nodeNum(head.as_mut().unwrap().right.take()) } } }
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }*/ import java.util.*; public class Solution { public int nodeNum(TreeNode head) { if(head==null){ return 0; } Queue<TreeNode> queue=new LinkedList<>(); queue.add(head); int sum=0; while(!queue.isEmpty()){ int size=queue.size(); sum+=size; for(int i=0;i<size;i++){ TreeNode node=queue.poll(); if(node.left!=null){ queue.add(node.left); } if(node.right!=null){ queue.add(node.right); } } } return sum; } }
package main import . "nc_tools" /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * * @param head TreeNode类 * @return int整型 */ func nodeNum( head *TreeNode ) int { ans:=0 var order func(*TreeNode) order=func(root *TreeNode){ if root==nil{ return } ans++ order(root.Left) order(root.Right) } order(head) return ans }
因为是完全二叉树,直接数最后一层的个数就行了,最后一层的个数等于2**height - (遇到的叶子节点个数) class Solution: count = 0 def nodeNum(self , head: TreeNode) -> int: # write code here def height(head): if not head: self.count += 1 return 0 return max(height(head.left), height(head.right)) + 1 h = height(head) ret = 0 for i in range(h): ret += 2**i lastLevel = 2**h return ret - (lastLevel - self.count)
function nodeNum( head ) { // write code here let queue = []; let count = 0; if(head==null) return count; queue.push(head); while(queue.length>0){ let len = queue.length; count = len+count; while(len--){ let node = queue.shift(); if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); } } return count; }
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }*/ import java.util.*; public class Solution { public int nodeNum(TreeNode root) { // write code here if(root==null){ return 0; } Queue<TreeNode> queue=new LinkedList<>(); queue.offer(root); int res=0; while(!queue.isEmpty()){ int n=queue.size(); res+=n; //ArrayList<Integer> tem=new ArrayList<>(); for(int i=0;i<n;i++){ TreeNode cur=queue.poll(); //tem.add(cur.val); if(cur.left!=null){ queue.offer(cur.left); } if(cur.right!=null){ queue.offer(cur.right); } } //res.add(tem); } return res; } }