算法系列——Binary Tree Inorder Traversal

题目描述

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

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

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

解题思路

两种方法,递归法和非递归法。实现思路和Binary Tree Preorder Traversal 类似。

程序实现

递归

public class Solution {
    private List result=new ArrayList();
    public List inorderTraversal(TreeNode root) {
        if(root==null)
            return result;
        inorder(root);
        return result;
    }
    private void inorder(TreeNode root){
        if(root==null)
            return ;
        inorder(root.left);
        result.add(root.val);
        inorder(root.right);
    }



}

非递归

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<Integer>();
         if(root==null)
            return result;
        Stack<Command> stack=new Stack<Command>();
        stack.push(new Command("go",root));
        while(!stack.isEmpty()){
            Command command=stack.pop();
            if("print".equals(command.s))
                result.add(command.node.val);
            else{
                if(command.node.right!=null)
                    stack.push(new Command("go",command.node.right));
                 stack.push(new Command("print",command.node));
                if(command.node.left!=null)
                    stack.push(new Command("go",command.node.left));

            }

        }
        return result;
    }

}
class Command{
    String s;
    TreeNode node;
    Command(String s,TreeNode node){
        this.s=s;
        this.node=node;
    }
}

你可能感兴趣的:(算法,算法系列)