递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
else{
int m = countNodes(root.left);
int n = countNodes(root.right);
return (m+n)+1;
}
}
}
非递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Stack;
class Solution {
public int countNodes(TreeNode root) {
int count=0;
Stack<TreeNode> stack = new Stack<>();
do{
while(root!=null){
count++;
stack.push(root);
root = root.left;
}
if(!stack.isEmpty()){
root = stack.pop();
root = root.right;
}
}while(!stack.isEmpty() || root!=null);
return count;
}
}