2015年2月15日星期日

Lintcode--Binary Tree preorder Traversal

public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> ans = new LinkedList<Integer>();
    if (root == null) return ans; //recursive 
    Stack<TreeNode> stack = new Stack<TreeNode>(); //using stack LIFO
    
stack.push(root);
    
while (!stack.isEmpty()) {
        TreeNode cur = stack.pop(); using pop to get the value of root of first
        ans.add(cur.val);
        // should it do reversely, right?
        if (cur.right != null) stack.push(cur.right);
        if (cur.left != null) stack.push(cur.left); //Last in First Out 
    }
    return ans;
}
Binary Tree: 
Preorder Traversal: DLR
Inorder Traversal: LDR
Post Order Traversal: RLD

没有评论:

发表评论