LeetCode94-二叉树的中序遍历
题目
解法
方法一:递归
方法二:迭代
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
if(root == null) return res;
Stack<TreeNode> st = new Stack<>();
TreeNode cur = root;
while(!st.isEmpty()||cur!=null){
if(cur==null&&!st.isEmpty()){
TreeNode temp = st.pop();
res.add(temp.val);
cur = temp.right;
}
if(cur == null&&st.isEmpty()) return res;
if(cur!=null){
st.push(cur);
cur = cur.left;
}
}
return res;
}
}