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]
.
Java代码
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- 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);
- }
- }
- }
Java代码
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- 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
时间: 2024-09-15 00:14:43