Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- public int countNodes(TreeNode root) {
- // Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
- // int count = 0;
- // TreeNode curr = root;
- // while(curr != null || !stack.isEmpty()){
- // while(curr != null){
- // stack.push(curr);
- // curr = curr.left;
- // }
- // count++;
- // curr = stack.pop();
- // curr = curr.right;
- // }
- // return count;
- /**
- So the bellow implementation teaches you that when youre carrying through an addable
- number you dont need a new method to include it in the signature para pasarlo,
- you can just make it en la funcion y lo seteas a 1 y le sumas a esa variable el
- resultado de la proxima iteracion. base case es cuando sea nulo, return 0;
- this way you dont have to only do half the tree and ending it with a return.
- you can just add all of it to the 'global' variable and return that in the end
- from the first call;
- **/
- //current sum (assuming root is not null)
- int sum = 1;
- //base case
- if (root == null) return 0;
- //check left
- if (root.left != null) {
- //add left subtree to sum
- sum += countNodes(root.left);
- }
- //check right
- if (root.right != null) {
- //add right subtree to sum
- sum += countNodes(root.right);
- }
- //result
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement