上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
}
};
php 解法, 执行用时: 36 ms, 内存消耗: 22.5 MB, 提交时间: 2021-05-13 10:38:46
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return Integer
*/
function countNodes($root) {
if ( $root == null ) return 0;
return $this->countNodes($root->left) + 1 + $this->countNodes($root->right);
}
}
golang 解法, 执行用时: 20 ms, 内存消耗: 7.1 MB, 提交时间: 2020-11-24 23:18:32
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func countNodes(root *TreeNode) int {
if root == nil {
return 0
}
level := 0
for node := root; node.Left != nil; node = node.Left {
level++
}
return sort.Search(1<<(level+1), func(k int) bool {
if k <= 1<<level {
return false
}
bits := 1 << (level - 1)
node := root
for node != nil && bits > 0 {
if bits&k == 0 {
node = node.Left
} else {
node = node.Right
}
bits >>= 1
}
return node == nil
}) - 1
}
python3 解法, 执行用时: 88 ms, 内存消耗: 20.6 MB, 提交时间: 2020-11-24 23:13:21
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes(self, root: TreeNode) -> int:
if root is None:
return 0
return self.countNodes(root.left) + self.countNodes(root.right) + 1