LeetCode题目-144

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2022-08-06 23:29:10

简介 LeetCode题目-144


✏Leetcode基础刷题之(150. Evaluate Reverse Polish Notation)


✏描述

使用非递归来完成二叉树的前序遍历。

✏题目实例

✏题目分析

前序遍历,先访问根结点,然后在访问左子树,最后访问右子树。可以利用栈的特点,这里我结合了队列和栈的特点来实现。先压入树,取出根节点。先把根节点值push到队列中,然后把右子树压入栈中,最后压入左子树。返回队列。当然你可以调整成你想要的实现方式。

     /**
      * Definition for a binary tree node.
      * class TreeNode {
      *     public $val = null;
      *     public $left = null;
      *     public $right = null;
      *     function __construct($value) { $this->val = $value; }
      * }
      */
     
     class Solution {
     
         /**
          * @param TreeNode $root
          * @return Integer[]
          */
         function preorderTraversal($root) {
             $res=[];
             $list=[];
             array_unshift($res,$root);
             while(!empty($res)){
                $current=array_shift($res);
                if($current==null) continue;
                 array_push($list,$current->val);
                 array_unshift($res,$current->right);
                 array_unshift($res,$current->left);           
             }
             return $list;
             
         }
     }

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云