Inoder traversal means that traverse the left subtree of current node first, than display current node's value, afterwards traverse the right subtree of current node.

1. Recursive method is easy to get, if node == null, return. traverse the left child recursively using the in-order traverse. Then add current node's value into the list. Afterwards, traverse the right child recursively using the in-order traverse.

2. Iteratively method using stack. Use a while loop, the condition of the loop is that either the current node is not null or the stack is not empty. If current node is not null, push it into the stack. If the node is null, this means we've gone to the leftmost of the remaining tree, then the pop the leftmost of the remain tree add its value to list, then get its right child and push it into the stack. By doing this iteratively, we can achieve in-order traversing the tree.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /* Recursion methond
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorderAddNode(root, list);
        return list;
    }
    public void inorderAddNode(TreeNode node, List<Integer> list){
        if(node == null) return;
        inorderAddNode(node.left, list);
        list.add(node.val);
        inorderAddNode(node.right, list);
    }
    */
    public List<Integer> inorderTraversal(TreeNode root){
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur !=null || !stack.isEmpty()){
            while(cur!=null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        return list;
    }
}

 

posted on 2016-01-27 04:33  爱推理的骑士  阅读(115)  评论(0编辑  收藏  举报