东寻

导航

leetcode| 94. 二叉树的中序遍历

##给定一个二叉树,返回它的中序遍历。 示例:

输入: [1,null,2,3]
1

2
/
3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗? 栈。

思路

时间复杂度O(n),空间复杂度O(lgn)。

递归代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private void recur(TreeNode root, List<Integer> ans) {
        if(root != null) {
            if(root.left != null) {
                recur(root.left, ans);
            }
            ans.add(root.val);
            if(root.right != null) {
                recur(root.right, ans);
            }
        }
    }
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<Integer>();
        recur(root, ans);
        return ans;
    }
}

非递归代码

/**
 * 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) {
        List<Integer> ans = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode curr = root;
        while(curr != null || !stack.isEmpty()) {
            while(curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            ans.add(curr.val);
            curr = curr.right;
        }
        return ans;
    }
}

链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

posted on 2020-02-16 22:10  东寻  阅读(155)  评论(0编辑  收藏  举报