LeetCode 94. Binary Tree Inorder Traversal 解题报告

来源:互联网 发布:启动顺序 windows boot 编辑:程序博客网 时间:2024/06/06 09:20

94. Binary Tree Inorder Traversal

My Submissions
Total Accepted: 109988 Total Submissions: 284121 Difficulty: Medium

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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    二叉树的中序遍历。递归解法自不必说,题目已经说明了,递归求解十分 trivial。要求用非递归方式求解!

    给出AC的递归和非递归代码

public class BinaryTreeInorderTraversal {public static void main(String[] args) {TreeNode n1 = new TreeNode(2);TreeNode n2 = new TreeNode(1);n1.left = n2;System.out.println(inorderTraversal(n1));}public static List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<Integer>();in(root, list);return list;}private void inRecursive(TreeNode root, List<Integer> l) {if (root == null)return;if (root.left != null)in(root.left, l);l.add(root.val);if (root.right != null)in(root.right, l);}private static void in(TreeNode root, List<Integer> l) {if (root == null)return;Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode cur = root;while (!stack.isEmpty() || cur != null) {if (cur != null) {stack.push(cur);cur = cur.left;} else {cur = stack.pop();l.add(cur.val);cur = cur.right;}}}}


0 0