More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/binary-tree-inorder-traversal/java
Given a binary tree, return the inorder traversal of its nodes' values.node
Example:post
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?ui
1. Recursionspa
2. Iterationcode
Recursionhtm
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); put(root, list); return list; } private void put(TreeNode node, List<Integer> list){ if(node==null) return; put(node.left, list); list.add(node.val); put(node.right, list); }
Iterationblog
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new LinkedList<>(); Stack<TreeNode> stk = new Stack<>(); while(root!=null || !stk.isEmpty()){ while(root!=null){ stk.push(root); root=root.left; } list.add(stk.peek().val); root = stk.pop().right; } return list; }
Time complexity : O(n)
ip
Space complexity : O(n)
More:【目錄】LeetCode Java實現