• 144. Binary Tree Preorder Traversal 二叉树先序遍历


    Given the root of a binary tree, return the preorder traversal of its nodes' values.

     

    Example 1:

    Input: root = [1,null,2,3]
    Output: [1,2,3]
    

    Example 2:

    Input: root = []
    Output: []
    

    Example 3:

    Input: root = [1]
    Output: [1]
    

    Example 4:

    Input: root = [1,2]
    Output: [1,2]
    

    Example 5:

    Input: root = [1,null,2]
    Output: [1,2]


    我的一个认知误区:前序遍历不是左中右,而是根结点 ---> 左子树 ---> 右子树,根节点在前面。
    前序的基础上,加一个list来辅助添加就行了

    参考:https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/45468/3-Different-Solutions

    public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> pre = new LinkedList<Integer>();
            preHelper(root,pre);
            return pre;
        }
        public void preHelper(TreeNode root, List<Integer> pre) {
            if(root==null) return;
            pre.add(root.val);
            preHelper(root.left,pre);
            preHelper(root.right,pre);
        }
     
     
  • 相关阅读:
    Go 接口
    Go 参数传递
    Go 结构体
    Go 指针
    使用ContentType处理大量的外键关系
    django的render的特殊用法
    restframework中的那些参数你知道吗?
    scrapy框架
    numpy如何使用
    HTML 5 audio标签
  • 原文地址:https://www.cnblogs.com/immiao0319/p/14998003.html
Copyright © 2020-2023  润新知