美文网首页
Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

作者: 无为无悔 | 来源:发表于2016-11-26 12:09 被阅读0次
  • 描述
    Given a binary tree, return the inorder traversal of its nodes’ values. For example: Given binary tree
    {1, #, 2, 3}, return [1, 3, 2].

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

  • 时间复杂度O(n),空间复杂度O(n)
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {
    public static List<Integer> inorderTraverse(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null)
            return result;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        while(p != null || !stack.isEmpty()) {
            if(p != null) {
                stack.push(p);
                p = p.left;
            }
            else {
                p = stack.pop();
                result.add(p.val);
                p = p.right;
            }
        }
        return result;
    }
}

相关文章

网友评论

      本文标题:Binary Tree Inorder Traversal

      本文链接:https://www.haomeiwen.com/subject/kqxgpttx.html