/**
* 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 {
Stack<TreeNode> stack = new Stack<>();
ArrayList<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return list;
while (!stack.isEmpty() || root != null){
while(root != null){
stack.push(root); //先将树顶端的压入栈中
root = root.left; //循环结束后,栈顶元素是最左端的元素,也符合中序遍历的思想
}
//其实在循环过程中,已经将路径上的中间结点压入了栈中
TreeNode node = stack.pop();//弹出最左端元素
list.add(node.val); //加入链表中
if (node.right != null){ //如果当前结点右右子树,那么右子树也要进行一样的处理
root = node.right;
}
}
return list;
}
}
非递归(迭代)实现二叉树的中序遍历
最新推荐文章于 2021-06-22 12:18:28 发布