给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
方法一:递归(最通俗易懂的方法)
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
findAns(root,res);
return res;
}
private void findAns(TreeNode root,List<Integer> res)
{
if(root!=null)
{
if(root.left!=null)
findAns(root.left,res);
res.add(root.val);
if(root.right!=null)
findAns(root.right,res);
}
}
}
方法二:用栈进行遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode>st=new Stack<TreeNode>();
List<Integer> res=new ArrayList<Integer>();
TreeNode cur=root;
while(cur!=null || !st.empty())
{
while(cur!=null)
{
st.push(cur);
cur=cur.left;
}
cur=st.pop();
res.add(cur.val);
cur=cur.right;
}
return res;
}
}
方法三:莫里斯遍历
具体细节讲解见官方题解的方法三:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<Integer>();
TreeNode cur=root;
TreeNode pre;
while(cur!=null)
{
if(cur.left==null)
{
res.add(cur.val);
cur=cur.right;
}
else
{
pre=cur.left;
while(pre.right!=null)
pre=pre.right;
pre.right=cur;
TreeNode temp=cur;
cur=cur.left;
temp.left=null;
}
}
return res;
}
}