222. Count Complete Tree Nodes

题目:
Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

解答:

public class Solution {
//学了enum的方法哈哈
public enum Direction {
LEFT, RIGHT
}

public int getDepth(TreeNode root, Direction dir) {
    int depth = 0;
    //这里是从root开始算起,所以求出来的结果是实际depth + 1
    while (root != null) {
        depth++;
        if (dir == Direction.LEFT) {
            root = root.left;
        } else {
            root = root.right;
        }
    }
    return depth;
}

public int countNodes(TreeNode root) {
    if (root == null) return 0;
    int leftDepth = getDepth(root, Direction.LEFT);
    int rightDepth = getDepth(root, Direction.RIGHT);

    if (leftDepth == rightDepth) {
        //1 

关键字:java, root, left, direction


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部