美文网首页
字节跳动 144. Binary Tree Preorder T

字节跳动 144. Binary Tree Preorder T

作者: 苦庭 | 来源:发表于2020-07-16 21:53 被阅读0次

    https://leetcode.com/problems/binary-tree-preorder-traversal/

    /**
     * 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 preorderTraversal = function(root) {
        let s = [];
        let p = root;
        let res = [];
        while(p!=null || s.length!=0){
            while(p!=null){
                res.push(p.val);
                s.push(p);
                p = p.left;
            }
            if(s.length!=0){
                p = s.pop();
                p = p.right;
            }
        }
        return res;
    };
    

    非递归方法重点要掌握先一路往左走(外while和内while),然后一边走一边入栈。接下来一路从底部往上走,如果能往上走(外while内if)就将指针切到右子节点去测试是否能更深一层走。

    相关文章

      网友评论

          本文标题:字节跳动 144. Binary Tree Preorder T

          本文链接:https://www.haomeiwen.com/subject/jozmhktx.html