94 二叉树的中序遍历
题目:给定一个二叉树的根节点 root
,返回 它的 中序 遍历 。
示例:
输入:root = [1,null,2,3]
输出:[1,3,2]
思考:
- 中序遍历需要遍历左子树,所以思考栈先存left
public class Solution {
/**
* 二叉树中序遍历
*/
public List<Integer> inorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
List<Integer> res = new LinkedList<>();
while (!stack.isEmpty() || root != null) {
// 栈中先压入所有的左子树
if (root != null) {
stack.push(root);
root = root.left;
} else {// 左子树遍历压入完成
// 依次出栈,每次出栈元素=最终结果,加入结果集中
root = stack.pop();
res.add(root.val);
// 遍历指针指向其右子树,重复压入其左子树的过程
root = root.right;
}
}
return res;
}
}