144. Binary Tree Preorder Traversal(二叉树的前序遍历)

简介: 题目练习二叉树的前序遍历

 题目地址:- LeetCode

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?

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [1,null,2,3]  

  1

   \

    2

   /

  3


输出: [1,2,3]


进阶: 递归算法很简单,你可以通过迭代算法完成吗?

非递归(迭代版):

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/classSolution {
publicList<Integer>preorderTraversal(TreeNoderoot) {
List<Integer>list=newArrayList<>();
Stack<TreeNode>stack=newStack<>();
while (root!=null||!stack.isEmpty()) {
while (root!=null) {
stack.push(root);
list.add(root.val);
root=root.left;
            }
root=stack.pop();
root=root.right;
        }
returnlist;
    }
}

image.gif

image.gif


递归版:

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/classSolution {
publicList<Integer>preorderTraversal(TreeNoderoot) {
List<Integer>list=newArrayList<>();
preorder(list, root);
returnlist;
    }
publicvoidpreorder(List<Integer>list, TreeNoderoot) {        
if (root==null) {
return ;
        }
list.add(root.val);
preorder(list, root.left);
preorder(list, root.right);
    }
}

image.gif

image.gif



Debug code in playground:

/* -----------------------------------*  WARNING:* -----------------------------------*  Your code may fail to compile*  because it contains public class*  declarations.*  To fix this, please remove the*  "public" keyword from your class*  declarations.*//*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/classSolution {
publicList<Integer>preorderTraversal(TreeNoderoot) {
List<Integer>list=newArrayList<>();
preorder(list, root);
returnlist;
    }
publicvoidpreorder(List<Integer>list, TreeNoderoot) {        
if (root==null) {
return ;
        }
list.add(root.val);
preorder(list, root.left);
preorder(list, root.right);
    }
}
publicclassMainClass {
publicstaticTreeNodestringToTreeNode(Stringinput) {
input=input.trim();
input=input.substring(1, input.length() -1);
if (input.length() ==0) {
returnnull;
        }
String[] parts=input.split(",");
Stringitem=parts[0];
TreeNoderoot=newTreeNode(Integer.parseInt(item));
Queue<TreeNode>nodeQueue=newLinkedList<>();
nodeQueue.add(root);
intindex=1;
while(!nodeQueue.isEmpty()) {
TreeNodenode=nodeQueue.remove();
if (index==parts.length) {
break;
            }
item=parts[index++];
item=item.trim();
if (!item.equals("null")) {
intleftNumber=Integer.parseInt(item);
node.left=newTreeNode(leftNumber);
nodeQueue.add(node.left);
            }
if (index==parts.length) {
break;
            }
item=parts[index++];
item=item.trim();
if (!item.equals("null")) {
intrightNumber=Integer.parseInt(item);
node.right=newTreeNode(rightNumber);
nodeQueue.add(node.right);
            }
        }
returnroot;
    }
publicstaticStringintegerArrayListToString(List<Integer>nums, intlength) {
if (length==0) {
return"[]";
        }
Stringresult="";
for(intindex=0; index<length; index++) {
Integernumber=nums.get(index);
result+=Integer.toString(number) +", ";
        }
return"["+result.substring(0, result.length() -2) +"]";
    }
publicstaticStringintegerArrayListToString(List<Integer>nums) {
returnintegerArrayListToString(nums, nums.size());
    }
publicstaticvoidmain(String[] args) throwsIOException {
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
Stringline;
while ((line=in.readLine()) !=null) {
TreeNoderoot=stringToTreeNode(line);
List<Integer>ret=newSolution().preorderTraversal(root);
Stringout=integerArrayListToString(ret);
System.out.print(out);
        }
    }
}

image.gif


===========================Talk is cheap, show me the code===========================


目录
相关文章
|
JavaScript
vue element plus Descriptions 描述列表
vue element plus Descriptions 描述列表
735 0
Ingress 开启 TLS / HTTPS 被忽略的细节
我们之前接入层用的SLB>Nginx ,考虑到Ingress和k8s的集成,我们用Ingress替代了Nginx,测试同学反馈在低版本浏览器上报错。
5379 0
|
小程序 API 开发工具
Mpay: 真的找到啦,后台一直有同学想要解决个人免签收款的问题,这款专注于个人免签收款,轻量级且高效的支付解决方案
嗨,大家好,我是小华同学。mpay是一个基于微信支付官方SDK封装的库,简化了微信支付集成过程,支持公众号、扫码、小程序支付等场景。它提供简洁API、全面错误处理和灵活配置选项,适用于电商网站、线下实体店和移动应用,提升支付体验和运营效率。
919 58
|
11月前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
423 104
我的Qt作品(3)基于QTabWidget和AdvancedDocking实现的Ribbon风格主界面【开源】
我的Qt作品(3)基于QTabWidget和AdvancedDocking实现的Ribbon风格主界面【开源】
2550 0
我的Qt作品(3)基于QTabWidget和AdvancedDocking实现的Ribbon风格主界面【开源】
|
Linux Serverless iOS开发
CentOS上部署node报错:node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
CentOS上部署node报错:node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
1155 0
CentOS上部署node报错:node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
|
Linux
Linux命令(58)之uname
Linux命令(58)之uname
394 1
|
SQL Java 关系型数据库
Eclipse中java获得mysql的查询结果集
不废话,先上代码,再上解释说明   1 package com.ningmeng; 2 3 import java.sql.*; 4 /** 5 * 1:获取查询结果集 6 * @author biexiansheng 7 * 8 */ 9 pub...
1079 0
|
SQL 安全 PHP
探寻PHP的现代演进之路:从Web开发到框架创新——揭秘PHP语言如何引领技术潮流
【8月更文挑战第2天】探索PHP的现代演进:从Web开发到框架创新
222 1