LeetCode刷题记录

LeetCode 144. 二叉树的前序遍历

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

144. 二叉树的前序遍历

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-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> preorderTraversal(TreeNode root) {
        if (root == null) return new ArrayList<>();
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }

复杂度分析:

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

  1. 现将二叉搜索树的根节点压入栈中
  2. 出栈栈顶元素,在依次将右子树、左子树压入栈中
public static List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            list.add(cur.val);
            if (cur.right != null) stack.push(cur.right);
            if (cur.left != null) stack.push(cur.left);
        }
        return list;
    }

复杂度分析:

public static void main(String[] args) {
         int[] arr = {1, 2, 3};
         TreeNode treeNode = new TreeNode(arr);
         List<Integer> list = preorderTraversal(treeNode);
         StringBuilder res = new StringBuilder();
         res.append("前序遍历:[");
         for (int i = 0; i < list.size(); i++) {
             res.append(list.get(i));
             if (i != list.size() - 1) {
                 res.append(",");
             }
         }
         res.append("]");
         System.out.println(res.toString());
    }
前序遍历:[1,2,3]


上一篇 下一篇

猜你喜欢

热点阅读