先自定义一下二叉树的类:
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
一个代码里面同时实现二叉树的前序、中序、后序遍历:
以该二叉树为例
import java.util.ArrayList;
import java.util.List;
class PreorderTraversalSolution {
public stat服务器托管网ic void main(String[] args) {
//构建二叉树
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
Solution sol = new Solution();
// 前序、中序、后序
System.out.println(sol.preorderTraversal(root).toString()); //[1, 2, 4, 5, 3, 6]
System.out.println(sol.inorderTraversal(root).toString()); //[4, 2, 5, 1, 3, 6]
System.out.println(sol.postorderTraversal(root).toString()); //[4, 5, 2, 6, 3, 1]
}
}
class Solution {
//前序遍历
服务器托管网public List preorderTraversal(TreeNode root) {
List res = new ArrayList();
preorder(root, res);
return res;
}
public void preorder(TreeNode root, List res) {
if (root == null) {
return;
}
res.add(root.val);
preorder(root.left, res);
preorder(root.right, res);
}
//中序遍历
public List inorderTraversal(TreeNode root) {
List res = new ArrayList();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List res) {
if (root == null) {
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
//后序遍历
public List postorderTraversal(TreeNode root) {
List res = new ArrayList();
postorder(root, res);
return res;
}
public void postorder(TreeNode root, List res) {
if (root == null) {
return;
}
postorder(root.left, res);
postorder(root.right, res);
res.add(root.val);
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
背景分析 书籍是人类进步的阶梯,在信息高度发达而浮躁的当下,静下心来读书成为都市人群的新趋势, 很多读书社团应运而生,那么通过设计一款小程序,把读书会搬到手机上,通过小程序了解最热门的书单和作家,可以每天组织阅读打卡和评比;书友会时常组织书友进行线下活动,那么…