Leetcode基础刷题之(94. Binary Tree Inorder Traversal)

栏目: 数据库 · 发布时间: 5年前

内容简介:明天再更新一篇400以内树的题目,就差不多把400以内的树的题目刷完了。

明天再更新一篇400以内树的题目,就差不多把400以内的树的题目刷完了。

Leetcode基础刷题之 PHP 解析(98. Validate Binary Search Tree)

Leetcode基础刷题之(94. Binary Tree Inorder Traversal)

给定一个二叉树,返回其中序遍历:左->根->右,当然这道题要求的是用非递归来完成。前序后序在之前的一篇文章有非递归实现,特意留下中序,用递归和非递归一起实现。

对于树这种题目,我们一般都会利用栈和队列的特性来完成,递归的话定义一个辅助函数,我这里存储树的时候利用栈后进先出的特点,最后的值利用队列的特性。

/**
 * 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 inorderTraversal($root) {
       $res=[];
        $this->helper($root,$res);
        return $res;
    }
    
    function helper($root,&$res){
        if($root !=null){
            if($root->left !=null){
                $this->helper($root->left,$res);
            }
            array_push($res,$root->val);
            if($root->right !=null){
                $this->helper($root->right,$res);
            }
        }
    }
}

迭代

如果是迭代的话,套路还是一样的。先将根节点压入栈中,然后将其所有的左子节点依次压入栈中,取出栈顶元素,保存至队列中,再把指针指向他的右子节点上,如果存在右子节点,循环又把右子节点的左子节点压入栈中,保证了中序遍历的顺序。


    /**
     * @param TreeNode $root
     * @return Integer[]
     */
    function inorderTraversal($root) {
        $res=[];
        $data=[];
        while(!empty($res) || $root !=null){
            while($root !=null){
                array_unshift($res,$root);
                $root=$root->left;
            }
            $root=array_shift($res);
            array_push($data,$root->val);
            $root=$root->right;
        }
        return $data;
    }

Github整理地址:https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Machine Learning in Action

Machine Learning in Action

Peter Harrington / Manning Publications / 2012-4-19 / GBP 29.99

It's been said that data is the new "dirt"—the raw material from which and on which you build the structures of the modern world. And like dirt, data can seem like a limitless, undifferentiated mass. ......一起来看看 《Machine Learning in Action》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具