题目:给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
思路一:递归法。与前序遍历类似。
代码:
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
midOrder(root,result);
return result;
}
public void midOrder(TreeNode root,List<Integer> result){
if(root==null){
return;
}
midOrder(root.left,result);
result.add(root.val);
midOrder(root.right,result);
}
思路二:迭代法。与前序遍历类似。
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
if(root!=null)
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.peek();
if(node!=null){
stack.pop();
if(node.right!=null) stack.push(node.right);
stack.push(node);
stack.push(null);
if(node.left!=null) stack.push(node.left);
}
else{
stack.pop();
node=stack.peek();
stack.pop();
result.add(node.val);
}
}
return result;
}