您的位置:首页 > 编程语言 > Go语言

Binary Tree Inorder Traversal

2014-01-31 04:46 267 查看


Binary Tree Inorder Traversal

 Total Accepted: 8234 Total
Submissions: 24173My Submissions

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.

// recursive solution
public static ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if (root == null) return list;
inorderTraversalHelper(root, list);
return list;
}

private static void inorderTraversalHelper(TreeNode root, ArrayList<Integer> list) {
if (root == null) return;
inorderTraversalHelper(root.left, list);
list.add((int) root.val);
inorderTraversalHelper(root.right, list);
}

// iterator solution
public static ArrayList<Integer> inorderTraversal2(TreeNode root){
ArrayList<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(true){
while(root!=null){
stack.push(root);
root = root.left;
}
if(stack.isEmpty()) break;
root = stack.pop();
list.add((int)root.val);
root = root.right;
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode