94. [二叉树]二叉树的中序遍历
94. 二叉树的中序遍历
方法一:递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
inorderViste(root, ans);
return ans;
}
public void inorderViste(TreeNode root, List<Integer> list){
if (root == null){
return ;
}
inorderViste(root.left, list);
list.add(root.val);
inorderViste(root.right, list);
}
}
方法二:迭代
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
while (root != null || !stack.isEmpty()){
while(root != null){
stack.offer(root);
root = root.left;
}
root = stack.pollLast();
ans.add(root.val);
root = root.right;
}
return ans;
}
}

浙公网安备 33010602011771号