步驟:
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;
}
}
轉載自:http://blog.csdn.net/u013812939/article/details/47295311