• 144. Binary Tree Preorder Traversal


    /**
    * 144. Binary Tree Preorder Traversal
    * https://leetcode.com/problems/binary-tree-preorder-traversal/description/
    * @param {TreeNode} root
    * @return {number[]}
    * Preorder: 根-左-右
    */
    var preorderTraversal = function (root) {
      let stack = [], result = [];
      while (stack.length > 0 || root != null) {
        while (root != null) {
          stack.push(root);
          result.push(root.val);//save root first
          root = root.left;//push left node
        }
        root = stack.pop();
        root = root.right;
      }
      return result;
    };
     
    //java
    public List<Integer> preorderTraversal(TreeNode root) {
           Stack<TreeNode> stack = new Stack<TreeNode>();
            List<Integer> list = new ArrayList<Integer>();
            while (root!=null || !stack.empty()){
                while (root!=null){
                    stack.push(root);
                    list.add(root.val);
                    root = root.left;
                }
                 root = stack.pop();
                root = root.right;
            }
            return list;
        }
    

      

  • 相关阅读:
    Native RabbitMQ Direct Exchange
    RabbitMQ系列文章导读
    AbstractQueuedSynchronizer
    CountDownLatch和CyclicBarrier
    显示锁Lock
    《SeleniumBasic 3.141.0.0
    《SeleniumBasic 3.141.0.0
    《SeleniumBasic 3.141.0.0
    《SeleniumBasic 3.141.0.0
    《SeleniumBasic 3.141.0.0
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/10204328.html
Copyright © 2020-2023  润新知