用stack实现二叉树的中序遍历

来源:互联网 发布:地图示意图制作软件 编辑:程序博客网 时间:2024/06/06 14:22

二叉树的中序遍历

样例

给出二叉树 {1,#,2,3},

   1    \     2    /   3

返回 [1,3,2].

/** * 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; *     } * } */ import java.util.ArrayList;import java.util.Stack; public class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in ArrayList which contains node values.     */    public ArrayList<Integer> inorderTraversal(TreeNode root) {        // write your code here        ArrayList<Integer> result=new ArrayList<Integer>();        Stack<TreeNode> stack=new Stack<TreeNode>();        TreeNode curt=root;        while(curt!=null||!stack.empty()){            while(curt!=null){                stack.add(curt);                curt=curt.left;            }            curt=stack.peek();            result.add(curt.val);            stack.pop();            curt=curt.right;        }        return result;    }}


原创粉丝点击