144.二叉树的前序遍历

2020/10/31

# Heading

    144.二叉树的前序遍历 (opens new window)

    Tags: algorithms stack tree

    Langs: c cpp csharp golang java javascript kotlin php python python3 ruby rust scala swift typescript

    • algorithms
    • Medium (67.14%)
    • Likes: 446
    • Dislikes: -
    • Total Accepted: 222.3K
    • Total Submissions: 324.9K
    • Testcase Example: '[1,null,2,3]'

    给你二叉树的根节点 root ,返回它节点值的 前序遍历。

    示例 1:

    输入:root = [1,null,2,3]
    输出:[1,2,3]
    

    示例 2:

    输入:root = []
    输出:[]
    

    示例 3:

    输入:root = [1]
    输出:[1]
    

    示例 4:

    输入:root = [1,2]
    输出:[1,2]
    

    示例 5:

    输入:root = [1,null,2]
    输出:[1,2]
    

    提示:

    • 树中节点数目在范围 [0, 100]
    • -100 <= Node.val <= 100

    进阶:递归算法很简单,你可以通过迭代算法完成吗?

    /*
     * @lc app=leetcode.cn id=144 lang=javascript
     *
     * [144] 二叉树的前序遍历
     */
    
    // @lc code=start
    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var preorderTraversal = function(root) {
        const stack = [];
        const ret = [];
        let p = root
        while(p || stack.length){
            if(p){
                ret.push(p.val)
                stack.push(p)
                p = p.left
            }else{
                p = stack.pop();
                p = p.right;
            }
        }
        return ret
    };
    // @lc code=end
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37