zoukankan      html  css  js  c++  java
  • 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;
        }
    

      

  • 相关阅读:
    Android WIFI 启动流程(TIP^^)
    MVVM模式原则
    CoreData入门
    转:iOS绘制一个UIView
    CGBitmapContextCreate函数参数详解
    RACCommand
    ReactiveCocoa内存管理
    IOS TableView滑动不灵敏问题
    IOS数组的排序和筛选
    IOS取消performSelector警告
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/10204328.html
Copyright © 2011-2022 走看看