JS——二叉树的中序遍历

  • Post author:
  • Post category:其他


var inorderTraversal = function(root) {
//使用递归
    // const result = [];
    // const inorder=(root)=>{
    //     if(root==null){
    //         return 
    //     }
    //     else{
    //         inorder(root.left)
    //         result.push(root.val)
    //         inorder(root.right)
    //     }
    // }
    // inorder(root);
    // return result
//使用栈
    let res = [];
    let stk = [];
    while(root || stk.length){
        while(root){
            stk.push(root);
            root = root.left
        }
        root = stk.pop();
        res.push(root.val);
        root = root.right

    }
    return res
};



版权声明:本文为qq_45870740原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。