leetCode222完全二叉树的节点数

递归

/**
 * 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;
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_40553837/article/details/88793939