算法系列——Binary Tree Inorder Traversal

来源:互联网 发布:简述js的事件委托 编辑:程序博客网 时间:2024/06/16 07:44

题目描述

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<Integer> result=new ArrayList<Integer>();    public List<Integer> 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;    }}
原创粉丝点击