首页 > 其他 > 详细

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

时间:2021-07-11 11:15:46      阅读:20      评论:0      收藏:0      [点我收藏+]

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);
    }

 

 
 

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

原文:https://www.cnblogs.com/immiao0319/p/14998003.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!