Binary Tree Inorder Traversal, Leetcode 解题笔记

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

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

第一种最简单的方法是递归:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    ArrayList<Integer> ret = new ArrayList<Integer>();
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        inorder(root);
        return ret;
    }
    public void inorder(TreeNode root){
        if(root == null){
            return;
        }
        inorderTraversal(root.left);
        ret.add(root.val);
        inorderTraversal(root.right);
    }
    
}

但是这道题考察的是用迭代的方法解决这个问题:每次遇到node压到stack里,然后node向左孩子移动,如果是空,则从stack里弹出node,加入到结果列表中,然后向右孩子移动。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        Stack<TreeNode> s = new Stack<TreeNode>();
        if(root == null) return ret;
        while(!s.empty() || root != null){
            if(root != null){
                s.push(root);
                root = root.left;
            }
            else{
                root = s.pop();
                ret.add(root.val);
                root = root.right;
            }
        }
        return ret;
    }
    
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s