今天说下二叉树的前序遍历,先来一颗二叉树熟悉熟悉:
前序遍历:先输出该节点,然后输出左孩子,然后输出右孩子。
public class Tree {
//定义一颗树
public static class TreeNode{
int val;
//左孩子
private TreeNode left;
//右孩子
private TreeNode right;
TreeNode(int x){
val = x;
}
}
public static ListpreOrder(TreeNode root){
//结果
Listlist =new LinkedList<>();
//栈
Stackstack =new Stack<>();
if(root ==null){
return list;
}
stack.push(root);
while(!stack.isEmpty()){
//栈顶元素出栈
TreeNode treeNode =stack.pop();
list.add(treeNode.val);
//左孩子是否存在
if(treeNode.right!=null){
stack.push(treeNode.right);
}
//右孩子是否存在
if(treeNode.left!=null){
stack.push(treeNode.left);
}
}
return list;
}
public static 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);
//例如:上述初始化的二叉树,前序遍历输出1,2,4,5,3
Listintegers =preOrder(root);
System.out.println(integers);
}
}
感谢各位老铁阅读,更多请关注公众号:别明天就今天吧