Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}
,1 \ 2 / 3
return
[1,3,2]
.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root==null) {
return ret;
}
Stack<TreeNode> stk = new Stack<TreeNode>();
TreeNode cur = root;
while(!stk.isEmpty() || cur!=null){
if(cur!=null) {
stk.push(cur);
cur = cur.left;
} else {
TreeNode node = stk.pop();
ret.add(node.val);
cur = node.right;
}
}
return ret;
}
}
没有评论:
发表评论