題目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
分析:
中序遍歷的順序是左中右。由於左子樹遍歷完才能遍歷根節點,所以需要使用棧來存放有左子樹的根節點。
1. 找到樹中最左邊的節點,經過的節點全部壓入棧
2. 彈棧,訪問棧頂的節點,並將其右孩子壓入棧中
3. 順着棧頂節點的左子樹向下,路過的節點全部如棧
4. 重複步驟2 3的過程
Java代碼實現:
/**
* 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>();
if(root==null)
return result;
Stack<TreeNode> s = new Stack<TreeNode>();
s.push(root);
while(s.peek().left!=null)
s.push(s.peek().left);
while(!s.isEmpty())
{
TreeNode node = s.pop();
result.add(node.val);
if(node.right!=null)
{
s.push(node.right);
while(s.peek().left!=null)
s.push(s.peek().left);
}
}
return result;
}
}