Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
题意很简单
中序遍历 左 根 右
运用递归的方法
先创建一个list来储存节点
然后调用左node
根node
右node
其他序遍历也是同理
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if( root == null) return new ArrayList<>();
List<Integer> res = new ArrayList<>();
recursion(root.left,res);
res.add(root.val);
recursion(root.right,res);
return res;
}
public void recursion(TreeNode node, List<Integer> res){
if(node == null)return;
if(node.left!=null){
recursion(node.left,res);
}
res.add(node.val);
if(node.right!=null){
recursion(node.right,res);
}
}
}