94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

难度:medium

题目:给定二叉树,返回其中序遍历结点。(不要使用递归)

思路:栈

Runtime: 1 ms, faster than 55.50% of Java online submissions for Binary Tree Inorder Traversal.
Memory Usage: 36.2 MB, less than 100.00% of Java online submissions for Binary Tree Inorder Traversal.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                TreeNode node = stack.pop();
                result.add(node.val);
                root = node.right;
            }
        }
        
        return result;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018152334
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞