/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int countNodes(TreeNode root) { if (root == null) return 0; return countNodes(root.left) + countNodes(root.right) + 1; } }
This solution is O(n) in number of nodes in the binary tree and is a generic solution that can be used to solve any binary tree for that matter.
The fact that this is a complete binary tree, brings to my mind another solution approach with O((lg n)^2) solution which I'll share here very soon!
Until next time,
Stay Tuned and Happy Coding!
See ya later!!
No comments:
Post a Comment