94. Binary Tree Inorder Traversal

发布时间:2019-06-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的94. Binary Tree Inorder Traversal全部内容,希望文章能够帮你解决94. Binary Tree Inorder Traversal所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: