• [leetcode] Binary Tree Preorder Traversal


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

    Example:

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

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


    分析:也就是求二叉树的先序遍历。

    思路一:递归,DFS求解。比较简单

     1 class Solution {
     2     List<Integer> res = new ArrayList<Integer>();
     3     public List<Integer> preorderTraversal(TreeNode root) {
     4         helper(root);
     5         return res;
     6     }
     7     private void helper(TreeNode root){
     8         if ( root == null ) return ;
     9         res.add(root.val);
    10         helper(root.left);
    11         helper(root.right);
    12     }
    13 }

    思路二:非递归方法实现。真正面试如果考到二叉树的三种遍历方法,肯定是考非递归,也就是栈的方法来实现的。

    参考:https://www.cnblogs.com/boris1221/p/9398848.html

     1 class Solution {
     2     public List<Integer> preorderTraversal(TreeNode root) {
     3         List<Integer> list = new ArrayList<>();
     4         if ( root == null ) return list;
     5         Stack<TreeNode> stack = new Stack<>();
     6         stack.push(root);
     7         while ( !stack.isEmpty() ){
     8             while ( root != null ){
     9                 list.add(root.val);
    10                 stack.push(root);
    11                 root = root.left;
    12             }
    13             if ( !stack.isEmpty() ){
    14                 root = stack.pop().right;
    15             }
    16         }
    17         return list;
    18     }
    19 }
  • 相关阅读:
    Python 写入和读取Excel数据
    postman检查点详解
    禅道安装在不同系统下搭建步骤
    Linux下如何启动和关闭防火墙
    tomcat环境搭建
    Lniux下搭建LNMP环境
    Linux下搭建LAMP环境
    通过XAMPP导入WordPress网站建立个人博客
    在Windows下XAMPP的安装及使用教程
    linux 下安装配置xampp环境
  • 原文地址:https://www.cnblogs.com/boris1221/p/9810618.html
Copyright © 2020-2023  润新知