标签:des style blog color io ar for div sp
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?
难度:50
recursive 方法:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Integer> inorderTraversal(TreeNode root) { 12 ArrayList<Integer> res = new ArrayList<Integer>(); 13 if (root == null) return res; 14 helper(root, res); 15 return res; 16 } 17 18 public void helper(TreeNode root, ArrayList<Integer> res) { 19 if (root == null) { 20 return; 21 } 22 if (root.left != null) { 23 helper(root.left, res); 24 } 25 res.add(root.val); 26 if (root.right != null) { 27 helper(root.right, res); 28 } 29 } 30 }
Iterative method: 参考了一下网上的思路,其实就是用一个栈来模拟递归的过程。所以算法时间复杂度也是O(n),空间复杂度是栈的大小O(logn)。
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Integer> inorderTraversal(TreeNode root) { 12 ArrayList<Integer> result = new ArrayList<Integer>(); 13 if (root == null) return result; 14 LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); 15 while (root != null || !stack.isEmpty()) { 16 if (root != null) { 17 stack.push(root); 18 root = root.left; 19 } 20 else { 21 root = stack.pop(); 22 result.add(root.val); 23 root = root.right; 24 } 25 } 26 return result; 27 } 28 }
Leetcode: Binary Tree Inorder Transversal
标签:des style blog color io ar for div sp
原文地址:http://www.cnblogs.com/EdwardLiu/p/3972139.html