这道题学的是,求二叉树的深度,节点个数,在完全二叉树的基础上,怎么简化深度
以及完全二叉树求节点个数的优化
求二叉树的深度
private int countLevel(TreeNode root){
if(root == null){
return 0;
}
return Math.max(countLevel(root.left),countLevel(root.right)) + 1;
}
求二叉树的节点个数
public int countNodes(TreeNode root) {
if (root == null){
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
int lefth = dfs(root.left);
int righth = dfs(root.right);
if(lefth==righth) return (int)Math.pow(2,lefth) + countNodes(root.right);
else return (int)Math.pow(2,righth) + countNodes(root.left);
}
int dfs(TreeNode root){
int high = 0;
if(root==null) return 0;
while(root!=null){
high++;
root = root.left;
}
return high;
}
}