zoukankan      html  css  js  c++  java
  • 144、二叉树的前序遍历 | JS-栈的应用

    给你二叉树的根节点 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
     

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

     1 /**
     2  * Definition for a binary tree node.
     3  * function TreeNode(val, left, right) {
     4  *     this.val = (val===undefined ? 0 : val)
     5  *     this.left = (left===undefined ? null : left)
     6  *     this.right = (right===undefined ? null : right)
     7  * }
     8  */
     9 /**
    10  * @param {TreeNode} root
    11  * @return {number[]}
    12  */
    13 var preorderTraversal = function(root) {
    14     const res = []; 
    15     const stack = []; //新建一个栈
    16     if(root) stack.push(root);  //根结点存在则入栈
    17     while (stack.length) {
    18         const n = stack.pop();
    19         res.push(n.val);
    20         if(n.right) stack.push(n.right);  //右先入栈,左后入,出栈的时候正好反过来,符合前序遍历的顺序
    21         if(n.left) stack.push(n.left);
    22     }
    23     return res;
    24 };
  • 相关阅读:
    音律入门
    [转]MIDI常识20条
    Java使用代理服务器
    java8日期时间
    误删课表系统
    Uncaught Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)
    SpringBoot应用部署[转]
    如何学习新技术
    Maven使用archetype迅速生成项目骨架
    两个月打工总结
  • 原文地址:https://www.cnblogs.com/oaoa/p/14822719.html
Copyright © 2011-2022 走看看