• 二叉树的递归遍历(Javascript)


    3种常见的遍历方式如下:
    中序遍历:左子节点->根节点->右子节点
    先序遍历:根节点->左子节点->右子节点
    后序遍历:左子节点->右子节点->根节点

    为方便记忆,可以理解为根节点的相对位置
    中序:根节点出现在左右子树中间
    先序:根节点出现在子树之前
    后序:根节点出现在子树之后

    树节点的定义

    /**
     * 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 inorderTraversal = function(root) {
        if(root===null){
            return []
        }
        var res=new Array()
        const inorder=function(root) {
            if(!root){
                return
            }
            inorder(root.left)
            res.push(root.val)
            inorder(root.right)
        }
        inorder(root)
        return res
    };
    

    先序遍历:

    var preorderTraversal = function(root) {
        if(root===null){
            return []
        }
        var res=new Array()
        const preorder=function(root) {
            if(!root){
                return
            }
            res.push(root.val)
            preorder(root.left)
            preorder(root.right)
        }
        preorder(root)
        return res
    };
    

    后序遍历:

    var postorderTraversal = function(root) {
        if(root===null){
            return []
        }
        var res=new Array()
        const postorder=function(root) {
            if(!root){
                return
            }
            postorder(root.left)
            postorder(root.right)
            res.push(root.val)
        }
        postorder(root)
        return res
    };
    
  • 相关阅读:
    编程之美3.7 队列中最大值问题
    群聊天
    POJ 3384 Feng Shui 半平面交
    Fiberead
    熊猫资本李论:为何我不看好“轻轻家教”模式?_亿欧网_驱动创业创新
    轻轻家教_百度百科
    为什么我们要使用新型Web安全协议HSTS?
    http://www.doframe.com/jetoolweb/index.html
    http://www.16aspx.com/Code/Show/5352
    http://www.ybtsoft.com/
  • 原文地址:https://www.cnblogs.com/baebae996/p/13905343.html
Copyright © 2020-2023  润新知