中序遍曆二叉樹(js)

來源:互聯網
上載者:User

標籤:入棧   兩種   兩種方法   方法   解答   var   target   出棧   discus   

leetcode上刷到一題中序遍曆一顆二叉樹的題,兩種方法,使用遞迴或者棧

原題及解答:https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/164579/recursion-and-stack-solve-the-problem-by-js

中序遍曆:按照左,根,右的順序遍曆二叉樹

使用棧:先將根節點入棧,找到所有左節點入棧,直到沒有左節點為止,然後出棧存入結果數組,每出一個,對比該根節點的右子節點是否有左節點,若有則入棧,否則繼續出棧

代碼如下

var inorderTraversal=function(root){        var  res=[];        //棧          var s=[];        var p = root;            while (p || s.length>0) {            //直至左節點為空白,即沒有左節點為止            while (p) {                s.push(p);                p = p.left;            }            //出棧,存放根節點            p = s.pop();            res.push(p.val);            p = p.right;        }        return res;}

遞迴:

var inorderTraversal = function(root) {    var res=[];    inorder(root,res);    return res;};//按照左 根 右順序遍曆function inorder(root,res){    if(!root) return ;    inorder(root.left,res);    res.push(root.val);    inorder(root.right,res);}

 

中序遍曆二叉樹(js)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.