LeetCode算法题–二叉树的中序遍历
题目思路:
利用栈
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while(current != null || !stack.isEmpty()){
while(current != null){//把左树节点先压栈
stack.push(current);
current = current.left;
}
//实现中序
current = stack.pop();
list.add(current.val);
current = current.right;
}
return list;
}
}
执行结果:
哎,递归的方法还是理解不了.