Count Complete Tree Nodes
算一个完全树的节点个数
答案是抄的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class Solution { public int countNodes(TreeNode root) { int leftDepth = leftDepth(root); int rightDepth = rightDepth(root); if (leftDepth == rightDepth) return (1 << leftDepth) - 1; else return 1+countNodes(root.left) + countNodes(root.right); } private int rightDepth(TreeNode root) { // TODO Auto-generated method stub int dep = 0; while (root != null) { root = root.right; dep++; } return dep; } private int leftDepth(TreeNode root) { // TODO Auto-generated method stub int dep = 0; while (root != null) { root = root.left; dep++; } return dep; } } |
Leave A Comment