Showing posts with label BFS. Show all posts
Showing posts with label BFS. Show all posts

Thursday, July 24, 2014

Clone Graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

BFS: 用一个HashMap存储已经生成过的点,避免重复生成相同的点。
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) {
            return null;
        }
        
        HashMap<UndirectedGraphNode, UndirectedGraphNode> map = 
        new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        queue.offer(node);
        map.put(node, new UndirectedGraphNode(node.label));
        while (!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();
            UndirectedGraphNode newcur = map.get(cur);
            for (UndirectedGraphNode neig : cur.neighbors) {
                //if contains, this node has already been searched
                if (!map.containsKey(neig)) {
                    map.put(neig, new UndirectedGraphNode(neig.label));
                    queue.offer(neig);
                }
                newcur.neighbors.add(map.get(neig));
            }
        }
        return map.get(node);
    }
}

Tuesday, July 22, 2014

Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
     /    \
   15   7

return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]

]

BFS: 用两个stack来实现层遍历
public class Solution {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (root == null) {
            return res;
        }
        
        Stack<TreeNode> cur = new Stack<TreeNode>();
        Stack<TreeNode> next = new Stack<TreeNode>();
        cur.push(root);
        boolean reverse = true;
        
        while (!cur.isEmpty()) {
            ArrayList<Integer> level = new ArrayList<Integer>();
            while (!cur.isEmpty()) {
                TreeNode node = cur.pop();
                if (reverse) {
                    if (node.left != null) {
                        next.push(node.left);
                    }
                    if (node.right != null) {
                        next.push(node.right);
                    }
                } else {
                    if (node.right != null) {
                        next.push(node.right);
                    }
                    if (node.left != null) {
                        next.push(node.left);
                    }
                }
                level.add(node.val);
            }
            reverse = !reverse;
            Stack<TreeNode> temp = cur;
            cur = next;
            next = temp;
            res.add(level);
        }
        return res;
    }
}

Monday, July 21, 2014

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

DFS:
public class Solution {
    //Time: O(n)
    int min = Integer.MAX_VALUE;
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        getMin(root, 1);
        return min;
    }
    
    private void getMin(TreeNode root, int depth) {
        if (root.left == null && root.right == null) {
            min = Math.min(min, depth);
        }
        
        if (root.left != null) {
            getMin(root.left, depth + 1);
        }
        if (root.right != null) {
            getMin(root.right, depth + 1);
        }
    }
}
BFS:
public class Solution {
    //Time: O(n)
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int length = 1;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                if (cur.left == null && cur.right == null) {
                    return length;
                }
            }
            length++;
        }
        return length;
    }
}

Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
    1
   /  \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

DFS: 
public class Solution {
    //Time: O(n)
    private int sum = 0;
    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return sum;
        }
        getSum(root, 0);
        return sum;
    }
    
    private void getSum(TreeNode root, int cur) {
        cur = cur * 10 + root.val;
        if (root.left == null && root.right == null) {
            sum += cur;
            return;
        }
        if (root.left != null) {
            getSum(root.left, cur);
        }
        if (root.right != null) {
            getSum(root.right, cur);
        }
    }
}
BFS: 
public class Solution {
    //Time: O(n)
    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int sum = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        Queue<Integer> queuesum = new LinkedList<Integer>();
        queue.offer(root);
        queuesum.offer(root.val);
        
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            int cursum = queuesum.poll();
            if (cur.left != null) {
                queue.offer(cur.left);
                queuesum.offer(cursum * 10 + cur.left.val);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
                queuesum.offer(cursum * 10 + cur.right.val);
            }
            if (cur.left == null && cur.right == null) {
                sum += cursum;
            }
        }
        return sum;
    }
}

Thursday, July 17, 2014

Path Sum I && II

I: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
DFS: 
public class Solution {
    //Time: O(n)
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        return checkPath(root, root.val, sum);
    }
    
    private boolean checkPath(TreeNode root, int cur, int sum) {
        if (root.left == null && root.right == null) {
            if (cur == sum) {
                return true;
            }
            return false;
        }
        
        boolean left = false;
        boolean right = false;;
        if (root.left != null) {
            left = checkPath(root.left, cur + root.left.val, sum);
        }
        if (root.right != null) {
            right = checkPath(root.right, cur + root.right.val, sum);
        }
        return left || right;
    }
}

BFS: 
public class Solution {
    //Time: O(n)
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        Queue<Integer> queueSum = new LinkedList<Integer>();
        queue.offer(root);
        queueSum.offer(root.val);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            int cursum = queueSum.poll();
            if (cur.left != null) {
                queue.offer(cur.left);
                queueSum.offer(cursum + cur.left.val);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
                queueSum.offer(cursum + cur.right.val);
            }
            if (cur.left == null && cur.right == null && cursum == sum) {
                return true;
            }
        }
        return false;
    }
}

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

DFS: 
public class Solution {
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (root == null) {
            return res;
        }
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        path(res, tmp, root, sum);
        return res;
    }
    
    private void path(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp,
                      TreeNode root, int sum) {
        if (root.left == null && root.right == null) {
            tmp.add(root.val);
            if (sum == root.val) {
                res.add(new ArrayList(tmp));
            }
            tmp.remove(tmp.size() - 1);
            return;
        }   
        
        tmp.add(root.val);
        if (root.left != null) {
            path(res, tmp, root.left, sum - root.val);
        }
        if (root.right != null) {
            path(res, tmp, root.right, sum - root.val);
        }
        tmp.remove(tmp.size() - 1);
    }
}

Wednesday, July 16, 2014

Binary Tree Level Order Traversal I && II

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

用一个queue进行BFS。第二个只需把25行改成add(0, level)
public class Solution {
    //Time: O(n)  Space: O(n)
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (root == null) {
            return res;
        }
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> level = new ArrayList<Integer>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                level.add(cur.val);
                
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            res.add(level);
        }
        return res;
    }
}