Binary Tree Inorder Traversal
2014-01-31 04:46
267 查看
Binary Tree Inorder Traversal
Total Accepted: 8234 TotalSubmissions: 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;
}
相关文章推荐
- leetcode 105-106:Construct Binary Tree from Preorder and Inorder Traversal
- 66_leetcode_Binary Tree Inorder Traversal
- LeetCode_Binary Tree Inorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- DFS&Iteration Binary Tree Inorder Traversal
- [LeetCode]problem 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Binary Tree Inorder Traversal
- leetcode-Construct Binary Tree from Preorder and Inorder Traversal
- 经典:Construct Binary Tree from Preorder and Inorder Traversal:由先序中序构建二叉树
- [LeetCode] Binary Tree Inorder Traversal
- Data Structure Binary Tree: Inorder Tree Traversal without recursion and without stack!
- LeetCode:BInary Tree Inorder Traversal(二叉树的中序遍历)
- leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Binary Tree Inorder Traversal
- LeetCode之Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode刷题笔记】Binary Tree Inorder Traversal
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode---Construct Binary Tree from Inorder and Postorder Traversal
- leetcode题解:Construct Binary Tree from Preorder and Inorder Traversal (根据前序和中序遍历构造二叉树)