LeetCode刷题记录Java算法提高之LeetCode刷题

LeetCode 94. 二叉树的中序遍历

2019-07-17  本文已影响0人  TheKey_

94. 二叉树的中序遍历

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

示例:
输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]
进阶:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


static class TreeNode implements Comparable<TreeNode> {
        private Integer val;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int[] arr) {
            if (arr == null || arr.length == 0) throw new NullPointerException("array is empty");
            this.val = arr[0];
            TreeNode root = this;
            for (int i = 1; i < arr.length; i++) {
                add(root, arr[i]);
            }
        }


        public TreeNode add(TreeNode root, Integer val) {
            if (root == null) return new TreeNode(val);
            if (val.compareTo(root.val) < 0) root.left = add(root.left, val);
            if (val.compareTo(root.val) > 0) root.right = add(root.right, val);
            return root;
        }

         @Override
        public int compareTo(TreeNode o) {
            return this.val.compareTo(o.val);
        }

思路:

  1. 先遍历二叉搜索树的左子树
  2. 接下来遍历二叉搜索树的根节点
  3. 最后在遍历二叉搜索树的右子树
static List<Integer> list = new ArrayList<>();
    public static List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return list;
        inorderTraversal(root.left);
        list.add(root.val);
        inorderTraversal(root.right);
        return list;
    }

复杂度分析:

思路:使用栈的后进先出(LIFO)特性

image.png
public static List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        return list;
    }

复杂度分析:


上一篇下一篇

猜你喜欢

热点阅读