版权声明:本文为博主原创文章,未经博主允许不得转载。
难度:容易
要求:
给出一棵二叉树,返回其中序遍历
样例给出一棵二叉树
{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) {
// write your code here
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(node != null || !stack.isEmpty()){
if(node != null){
stack.push(node);
node = node.left;
}else{
node = stack.pop();
list.add(node.val);
node = node.right;
}
}
return list;
}
}