LeetCode刷题 Day14

61 阅读1分钟

LeetCode刷题 Day14

144. Binary Tree Preorder Traversal

Given the root of a binary tree, return the preorder traversal of its nodes' values.

Example 1:

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

递归代码:

var preorderTraversal = function(root) {
    let res = [];    
    
    var helper = function(root) {
        if (!root) return;
        res.push(root.val);
        helper(root.left);
        helper(root.right);
    }
    
    helper(root);
    return res;
};

迭代代码:

var preorderTraversal = function(root) {
    let res = [];    
    let stack = [];
    if (root) stack.push(root);
    while (stack.length > 0) {
        const node = stack.pop();
        res.push(node.val);
        if (node.right) {
            stack.push(node.right);
        }

        if (node.left) {
            stack.push(node.left);
        }
    }
    
    return res;
};

时间复杂度: O(n) 空间复杂度: O(n) (递归也是入栈操作)


94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes' values.

  Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

递归代码:

var inorderTraversal = function(root) {
    let res = [];
    
    var helper = function(root) {
        if (!root) return;
        
        helper(root.left);
        res.push(root.val);
        helper(root.right);
    }
    
    helper(root);
    return res;
};

迭代代码:

var inorderTraversal = function(root) {
    let res = [];
    let stack = [];    
    let node = root;
    
    while (node || stack.length > 0) {
        if (node) {
            stack.push(node);
            node = node.left;
        } else {
            node = stack.pop();
            res.push(node.val);
            node = node.right;
        }
    }
    
    return res;
};

时间复杂度: O(n) 空间复杂度: O(n)


145. Binary Tree Postorder Traversal

Given the root of a binary tree, return the postorder traversal of its nodes' values.

Example 1:

Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

递归代码:

var postorderTraversal = function(root) {
    let res = [];
    
    var helper = function(root) {
        if (!root) return;
        
        helper(root.left);
        helper(root.right);
        
        res.push(root.val);
    }    
    helper(root);
    return res;
};

迭代代码:

var postorderTraversal = function(root) {
    let stack = [];
    let tmp = [];
    let res = [];
    
    if (root) stack.push(root);
    
    while (stack.length) {
        let node = stack.pop();
        tmp.push(node.val);
        if (node.left) stack.push(node.left);
        if (node.right) stack.push(node.right);
    }
    
    for (let i = tmp.length - 1; i >= 0; i--) {
        res.push(tmp[i]);
    }
    
    return res;
};

时间复杂度: O(n) 空间复杂度: O(n)