Binary Tree Inorder Traversal

来源:互联网 发布:上海移动网络怎么样 编辑:程序博客网 时间:2024/05/23 11:47

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 a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> list = new LinkedList<Integer>();        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode cur = root;        while(cur != null || !stack.isEmpty()){            while(cur != null){                stack.push(cur);                cur = cur.left;            }            cur = stack.pop();            list.add(cur.val);            cur = cur.right;        }        return list;    }}

Inorder 左根右,preorder根左右,postorder 左右根



0 0