Leetcode Binary Tree Inorder Traversal 二叉树中序遍历


题目:


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 inorderTraversal(TreeNode root) {
        List result = new ArrayList();
        if(root==null)
            return result;
            
        Stack s = new Stack();
        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;
    }
}


你可能感兴趣的:(LeetCode)