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
Inorder: return
[1,3,2]
. 左中右
addAll 是因为arraylist result 里面应该添加int
第一种是递归的算法,时间复杂度是O(n), 而空间复杂度则是递归栈的大小,即O(logn)。
第二种是迭代的算法, 用栈来实现。 时间复杂度是O(n), 空间O(logn)第三种是分治算法
public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } helper(res, root); return res; } public void helper(List<Integer> res, TreeNode root) { if (root == null) { return; } helper(res, root.left); res.add(root.val); helper(res, root.right); } } public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } Stack<TreeNode> stack = new Stack<TreeNode>(); while (!stack.isEmpty() || root != null) { if (root != null) { stack.push(root); root= root.left; } else { root = stack.pop(); res.add(root.val); root = root.right; } } return res; } } public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } List<Integer> left = inorderTraversal(root.left); List<Integer> right = inorderTraversal(root.right); res.addAll(left); res.add(root.val); res.addAll(right); return res; } }
没有评论:
发表评论