1. 程式人生 > >LintCode Binary Tree Inorder Traversal 二叉樹的中序遍歷(非遞迴)

LintCode Binary Tree Inorder Traversal 二叉樹的中序遍歷(非遞迴)

給出一棵二叉樹,返回其中序遍歷。
Given a binary tree, return the inorder traversal of its nodes’ values.

樣例
給出二叉樹 {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;
 *     }
 * }
 */
public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new
Stack<TreeNode>(); TreeNode p = root; while(p != null || !stack.empty()) { while(p != null) { stack.push(p); p = p.left; } if(!stack.empty()) { p = stack.pop(); list.add(p.val); p = p.right; } } return
list; } }