LeetCode算法题——完全二叉树的节点个数

对于这道题首先会想到递归判断节点,不为空就加1,代码如下(但是会超时):

//会超时
public class Solution {
    if (root == null) return 0;
    return CountNodes(root.left) + CountNodes(root.right) + 1;
}

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) { val = x; }
}

因为完全二叉树除了最后一层,它的上面都是满节点的,所以就有了如下的代码(可以通过):

public class Solution {
    public int CountNodes(TreeNode root) {
        if (root == null) return 0;
            TreeNode left = root;
            TreeNode right = root;
            int l = 0;   //左节点的高度
            int r = 0;   //右节点的高度
            while (left != null) {
                l++;
                left = left.left;
            }
            while (right != null)
            {
                r++;
                right = right.right;
            }
            //如果左右相等则是满二叉树根据公式可得
            if (l == r) return (int)Math.Pow(2, l) - 1;
            return CountNodes(root.left) + CountNodes(root.right) + 1;
    }
}

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) { val = x; }
}

猜你喜欢

转载自blog.csdn.net/m0_37845126/article/details/82665961