题解 | #二叉树的中序遍历#
二叉树的中序遍历
https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d
public class Solution {
public int[] inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
TreeNode p = root;
while (p != null || !stack.isEmpty()) {
if (p != null) {
// 一直先找左孩子
stack.push(p);
p = p.left;
} else {
// 该节点没有左孩子,就去看是否有右孩子
p = stack.pop();
list.add(p.val);
p = p.right;
}
}
int len = list.size();
int[] arr = new int[len];
for (int i = 0; i < len; i ++)
arr[i] = list.get(i);
return arr;
}
}
细品就OK

