java二叉樹非遞迴之中序遍歷
阿新 • • 發佈:2019-01-24
思路:使用輔助棧改寫遞迴程式,中序遍歷沒有前序遍歷好寫,其中之一就在於入棧出棧的順序和限制規則。我們採用「左根右」的訪問順序可知主要由如下四步構成。
步驟:
1.首先需要一直對左子樹迭代並將非空節點入棧
2.節點指標為空後不再入棧
3.當前節點為空時進行出棧操作,並訪問棧頂節點
4.將當前指標p用其右子節點替代
步驟2,3,4對應「左根右」的遍歷結構,只是此時的步驟2取的左值為空。
步驟:
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; } }