leetcode分类下所有的题解均为作者本人经过权衡后挑选出的题解,在易读和可维护性上有优势
每题只有一个答案,避免掉了太繁琐的以及不实用的方案,所以不一定是最优解
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root != null) inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res){
if(root.left != null) inorder(root.left, res);
res.add(root.val);
if(root.right != null) inorder(root.right, res);
}
}
思路:
- 如果root不为空,就带上一个空的res扔给inorder处理吧
- 前中后序遍历的递归写法非常简单,只需更改res.add(root.val)的位置即可,原理就是根据三种遍历方式的规则来的