zoukankan      html  css  js  c++  java
  • leetcode -- Binary Tree Preorder Traversal

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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,2,3].

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

    [解题思路]

    递归解法

     1 public ArrayList<Integer> preorderTraversal(TreeNode root) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         ArrayList<Integer> result = new ArrayList<Integer>();
     5         
     6         preorder(root, result);
     7         
     8         return result;
     9     }
    10     
    11     public void preorder(TreeNode root, ArrayList<Integer> result){
    12         if(root != null){
    13             result.add(root.val);
    14             preorder(root.left, result);
    15             preorder(root.right, result);
    16         }
    17     }

    [非递归解法]

    1)访问节点cur,并将节点cur入栈;

    2)判断节点cur的左孩子是否为空,若为空,则取栈顶节点并进行出栈操作,并将栈顶节点的右孩子置为当前节点cur,循环至1);若不为空,则将cur的左孩子置为当前节点cur;

    3)知道cur为null并且栈为空,则遍历结束

     1 public ArrayList<Integer> preorderTraversal(TreeNode root) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         ArrayList<Integer> result = new ArrayList<Integer>();
     5         if(root == null){
     6             return result;
     7         }
     8         
     9         Stack<TreeNode> stack = new Stack<TreeNode>();
    10         TreeNode cur = root;
    11         while(cur != null || !stack.empty()){
    12             
    13             while(cur != null){
    14                 result.add(cur.val);
    15                 stack.push(cur);
    16                 cur = cur.left;
    17             }
    18             
    19             if(!stack.empty()){
    20                 cur = stack.pop();
    21                 // if(cur.right != null){
    22                     cur = cur.right;
    23                 // }
    24             }
    25         }
    26         
    27         return result;
    28     }
  • 相关阅读:
    springboot+websocket 归纳收集
    flask-admin 快速打造博客 系列一
    Flask-sqlalchemy 语法总结
    python 小问题收集
    pyenv+virtual 笔记
    flask_admin 笔记七 扩展功能
    Flask_admin 笔记六 modelView的内置方法
    spring boot 项目中 maven打第三方lib包时遇到的问题以及解决方法
    java 字符串压缩长度并解压
    highcharts中放aqi及6要素,再加上气象5要素的图
  • 原文地址:https://www.cnblogs.com/feiling/p/3426172.html
Copyright © 2011-2022 走看看