中序遍历(递归)
public void inorder(TreeNode root,List<Integer> list){
if(root == null) return;
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<>();
inorder(root,list);
return list;
}
(非递归)
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
//利用栈来完成中序遍历
Stack<TreeNode> stack = new Stack<>();
//遍历每一个元素
while(root != null || !stack.empty()){
//先遍历到左子树的最左边节点 之后就弹出元素 再去放弹出元素的右节点 再去判断 以达到左根右的遍历顺序
if( root != null){
stack.push(root);
root = root.left;
}else{
root=stack.pop();
list.add(root.val);
root=root.right;
}
}
return list;
}
}