zoukankan      html  css  js  c++  java
  • [Algorithm] 94. Binary Tree Inorder Traversal iteratively approach

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

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,3,2]

    Follow up: Recursive solution is trivial, could you do it iteratively?

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    
    function getLefts(root) {
        if (!root) {
            return [];
        }
        
        let result = [];
        let current = root;
        while(current) {
            result.push(current);
            current = current.left ;
        }
        
        return result;
    }
    
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var inorderTraversal = function(root) {
        let lefts = getLefts(root);
        let result = [];
        while (lefts.length) {
            let newRoot = lefts.pop();
            result.push(newRoot.val);
            if (newRoot.right) {
                let newLefts = getLefts(newRoot.right);
                lefts = lefts.concat(newLefts)
            }
        }
        
        return result;
    };

    The idea is 

    • get all the left side node and push into stack
    • because stack is first in last out, when we do pop(), we are actually start from bottom of the tree.
    • everytime, we pop one node from stack, we check its right child, get all the left nodes from this right child and append into stack.
    • in this way, we are able to track all the node.
  • 相关阅读:
    BZOJ 1069 最大土地面积
    BZOJ 1059 矩阵游戏
    BZOJ 3570 动物园
    Luogu 3934 Nephren Ruq Insania
    Luogu 3233 [HNOI2014]世界树
    CF613D Kingdom and its Cities
    Luogu 4001 [BJOI2006]狼抓兔子
    Luogu 2824 [HEOI2016/TJOI2016]排序
    POJ 3463 Sightseeing
    Luogu 2495 [SDOI2011]消耗战
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11992069.html
Copyright © 2011-2022 走看看