LeetCode Count Complete Tree Nodes

来源:互联网 发布:js字符串去重 编辑:程序博客网 时间:2024/05/29 17:26

原题链接在这里:https://leetcode.com/problems/count-complete-tree-nodes/

递归调用函数,终止条件两个,一个是root == null, return 0, 一个是左右高度相同说明是满树,return 2^height-1。

若是左右高度不同,递归调用求左子树包含Node数+右子树包含Node数+1(自身)。

Time O(logn * logn), worst case对于每一层都要求一遍当前点到leaf得深度. Space O(logn) recursion.

Note: 1. 用Math.pow(), 注意arguments 和 return type 都是double, 此处会TLE.

2. 用<<来完成幂运算,但注意<<的precedence比+,-还要低,需要加括号。

AC  Java:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int countNodes(TreeNode root) {        if(root == null){            return 0;        }        TreeNode p = root;        TreeNode q = root;        int heightL = 0;        int heightR = 0;        while(p != null){            p = p.left;            heightL++;        }        while(q != null){            q = q.right;            heightR++;        }        if(heightL == heightR){            return (1<<heightL)-1;        }else{            return 1 + countNodes(root.left) + countNodes(root.right);        }    }}


0 0