94. Binary Tree Inorder Traversal

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

Example:less

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

Output: [1,3,2]

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

難度:medium遞歸

題目:給定二叉樹,返回其中序遍歷結點。(不要使用遞歸)it

思路:棧io

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.ast

/**
 * 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;
    }
}
相關文章
相關標籤/搜索