递归遍历加迭代遍历
大概就是递归就改一下顺序注意一下List实现方式可以是ArrayList
迭代的话会比较麻烦要先得到最左的子节点然后pop并且把值add进去都得到它的父节点也就是根,然后再cur=cur.right 得到右子节点
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
inorder(root,result);
return result;
}
public void inorder(TreeNode root, List<Integer> result){
if(root == null){
return;
}
inorder(root.left,result);
result.add(root.val);
inorder(root.right,result);
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
if(root == null){
return result;
}
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();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}