1022. Sum of Root To Leaf Binary Numbers

1022. Sum of Root To Leaf Binary Numbers

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum = 0;
    public void construct(TreeNode root,String prev){
        if (root == null) return;
        if( root.left == null && root.right == null){
            sum+=Integer.parseInt(prev+root.val,2);
            return;
        }
       construct(root.left,prev+""+root.val);
       construct(root.right,prev+""+root.val);    
    }
    public int sumRootToLeaf(TreeNode root) {
        if (root == null) return 0;
        if(root.left == null && root.right == null) return root.val;
         construct(root.left,root.val+"");
         construct(root.right,root.val+"");
        return sum;
    }
}

107. Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List> levelOrderBottom(TreeNode root) {
        if (root == null) return new LinkedList();
        List<List> out = new ArrayList();
Queue   q = new LinkedList(); 
        q.offer(root);
        while(!q.isEmpty()){
            ArrayList current = new ArrayList();
            int size = q.size();//we must put it in variable is the size changes each loop
            for(int i =0; i < size; i++){
            TreeNode c = q.poll();
            if(c != null){
                current.add(c.val);
            if(c.left != null)
                q.offer(c.left);
            if(c.right != null)
                q.offer(c.right);
            }
            
        }
            out.add(current);
        }
         Collections.reverse(out);
        return out;
    }
    
}

101. Symmetric Tree

101. Symmetric Tree

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public static boolean isMirror(TreeNode r, TreeNode l){
        if( r == null && l == null) return true;
        if( r == null && l != null) return false;
        if( r != null && l == null) return false;
        if (r.val != l.val) return false;
        if (r.val == l.val) 
        return isMirror(l.right,r.left) && isMirror(l.left, r.right);
         else return false;
    }
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        
        return isMirror(root.right,root.left);
    }
}