代码如下
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
while(!stack.empty()||root!=null){
//首先不断吧左子节点放入,然后拿出来的时候判断有无右子节点,若有则取出再放入右子节点
if(root!=null){
stack.push(root);
}
while(root.left!= null){
stack.push(root);
root = root.left;
}
if(!stack.empty()){
root = stack.pop();
res.add(root.val);
}
if(root.right!=null){
//两个node
root = root.right;
}
}
return res;
}
}
然后报 超出内存限制,没发现哪里循环了啊