java二叉树非递归之中序遍历

来源:互联网 发布:smartgit linux 破解 编辑:程序博客网 时间:2024/05/20 18:45

思路:使用辅助栈改写递归程序,中序遍历没有前序遍历好写,其中之一就在于入栈出栈的顺序和限制规则。我们采用「左根右」的访问顺序可知主要由如下四步构成。

步骤:

1.首先需要一直对左子树迭代并将非空节点入栈
2.节点指针为空后不再入栈
3.当前节点为空时进行出栈操作,并访问栈顶节点
4.将当前指针p用其右子节点替代
步骤2,3,4对应「左根右」的遍历结构,只是此时的步骤2取的左值为空。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> result = new ArrayList<Integer>();        Stack<TreeNode> s = new Stack<TreeNode>();        while (root != null || !s.empty()) {            if (root != null) {                s.push(root);                root = root.left;            } else {                root = s.pop();                result.add(root.val);                root = root.right;            }        }        return result;    }}




0 0
原创粉丝点击