https://leetcode-cn.com/problems/count-complete-tree-nodes/
递归的题目,左右中的后序遍历思想。
/**
* 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 leftNum = countNodes(root.left); //统计左结点的个数
int rightNum = countNodes(root.right); //统计右节点的个数
int count = leftNum + rightNum + 1; //所有节点加起来
return count;
}
}