javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

144. 二叉树的前序遍历

Open Geekhyt opened this issue 5 years ago • 1 comments

原题链接

172e5c5eb83e4be9

前序遍历:先打印当前节点,再打印当前节点的左子树,最后打印当前节点的右子树 (ABCDEFG)

const preorderTraversal = function(root) {
    const result = [];
    function pushRoot(node){
        if (node !== null) {
            result.push(node.val);
            if (node.left !== null){ 
                pushRoot(node.left);
            }
            if (node.right !== null) {
                pushRoot(node.right);
            } 
        }
    }
    pushRoot(root);
    return result;
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

Geekhyt avatar Feb 01 '21 16:02 Geekhyt

遍历实现

利用栈的特性

var preorderTraversal = function(root) {
    const ret = []
    if (!root) return ret
    const stack = [root]
    while(stack.length) {
        const cur = stack.pop()
        ret.push(cur.val)
        if (cur.left) stack.push(cur.left)
        if (cur.right) stack.push(cur.right)
    }
    return ret
};

二叉树后序遍历同理,中序遍历稍有不同。

yuetong3yu avatar Mar 04 '21 01:03 yuetong3yu