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]
.
- public class Solution {
- public List<Integer> inorderTraversal(TreeNode root) {
- List<Integer> res = new ArrayList<>();
- dfs(root, res);
- return res;
- }
-
- private void dfs(TreeNode root, List<Integer> res) {
- if (root != null) {
- dfs(root.left, res);
- res.add(root.val);
- dfs(root.right, res);
- }
- }
- }
- public class Solution {
- public List<Integer> inorderTraversal(TreeNode root) {
- List<Integer> res = new ArrayList<>();
- if (root == null) {
- return res;
- }
- LinkedList<TreeNode> stack = new LinkedList<>();
- while (root!=null || !stack.isEmpty()) {
- if (root!=null) {
- stack.push(root);
- root = root.left;
- } else {
- root = stack.pop();
- res.add(root.val);
- root = root.right;
- }
- }
- return res;
- }
- }
http://hcx2013.iteye.com/blog/2230218
Binary Tree Inorder Traversal(转)
原文:http://www.cnblogs.com/softidea/p/4678973.html