Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

144. 二叉树的前序遍历 #14

Open
Geekhyt opened this issue Feb 1, 2021 · 1 comment
Open

144. 二叉树的前序遍历 #14

Geekhyt opened this issue Feb 1, 2021 · 1 comment
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 1, 2021

原题链接

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)
@yuetong3yu
Copy link

yuetong3yu commented Mar 4, 2021

遍历实现

利用栈的特性

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
};

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

@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants