您的位置:首页 > 其它

LeetCode 94. Binary Tree Inorder Traversal 解题报告

2016-02-18 10:59 441 查看


94. Binary Tree Inorder Traversal

My Submissions

Question

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;
			}
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: