题目
给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
题目地址:https://leetcode.cn/problems/binary-tree-inorder-traversal/
示例
方法1:递归
作者:本人
思路
中序遍历就是 左、中、右
所以调整递归时执行代码的顺序为:先向左递归、再输出根结点、再向右递归
同样适用前序遍历和后续遍历,只需要调整顺序即可
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
diGui(list,root);
return list;
}
void diGui(List<Integer> list,TreeNode root){
if (root!=null){
diGui(list,root.left);
list.add(root.val);
diGui(list,root.right);
}
}
}