二叉树的中序遍历
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
提供两种解法:
一:基于栈的中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
cur = stack.pop();
list.add(cur.val);
cur = cur.right;
}
}
return list;
}
法二:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
addList(root,list);
return list;
}
public void addList(TreeNode root,List list){
if(root!=null){
addList(root.left,list);
list.add(root.val);
addList(root.right,list);
}
}
}