2015年2月9日星期一

binary tree/ binary search tree

Binary Tree Template:
二叉树:

(1)Preorder
(2)Inorder
(3) Post order

Traversal

Template 1: Traverse

public class Solution {
    public void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        // do something with root
        traverse(root.left);
        // do something with root
        traverse(root.right);
        // do something with root
    }
}


Tempate 2: Divide & Conquer

public class Solution {
    public ResultType traversal(TreeNode root) {
        // null or leaf
        if (root == null) {
            // do something and return;
        }
        
        // Divide
        ResultType left = traversal(root.left);
        ResultType right = traversal(root.right);
        
        // Conquer
        ResultType result = Merge from left and right.
        return result;
    }
}

Stack and Queue: 

(1) Queue: FIFO 
(2) Stack: LIFO  



没有评论:

发表评论