LintCode: Binary Tree Inorder Traversal

Problem:

Given a binary tree, return the inorder traversal of its nodes' values.

Idea:

Same as the preorder, only difference is to visit the node between going for left and going for right.

Code:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    private ArrayList<Integer> result = new ArrayList<Integer>();
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        // handle corner cases
        if (root == null) {
            return result;
        }
        helper(root);
        return result;
    }
    private void helper(TreeNode node) {
        // condition to return
        if (node == null) {
            return;
        }
        // go for left
        helper(node.left);
        // refresh the result
        result.add(node.val);
        // go for right
        helper(node.right);
    }
}
View Code

 

posted on 2016-03-13 13:37  dingjunnan  阅读(110)  评论(0编辑  收藏  举报

导航