java 222.计算完整树节点(#)。java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 222.计算完整树节点(#)。java相关的知识,希望对你有一定的参考价值。
public int countNodes(TreeNode root) {
if (root == null)
return 0;
return 1 + countNodes(root.left) + countNodes(root.right)
class Solution {
public int countNodes(TreeNode root) {
if (root == null)
return 0;
TreeNode left = root, right = root;
int height = 0;
while (right != null) {
left = left.left;
right = right.right;
height++;
}
if (left == null)
return (1 << height) - 1;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
class Solution {
int height(TreeNode root) {
return root == null ? -1 : 1 + height(root.left);
}
public int countNodes(TreeNode root) {
int nodes = 0, h = height(root);
while (root != null) {
if (height(root.right) == h - 1) {
nodes += 1 << h;
root = root.right;
} else {
nodes += 1 << h-1;
root = root.left;
}
h--;
}
return nodes;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int height(TreeNode root) {
return root == null ? -1 : 1 + height(root.left);
}
public int countNodes(TreeNode root) {
int h = height(root);
return h < 0 ? 0 :
height(root.right) == h - 1 ? (1 << h) + countNodes(root.right) :
(1 << (h - 1)) + countNodes(root.left);
}
}
以上是关于java 222.计算完整树节点(#)。java的主要内容,如果未能解决你的问题,请参考以下文章
java 222.计算完整树节点(#)。java
java 222.计算完整树节点(#)。java
java 222.计算完整树节点(#)。java
java 222.计算完整树节点(#)。java
Java实现二叉搜索树
在Java中计算树中的节点