import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
/**
* 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
*
* @author pomay
*
*/
public class Solution_cengcibianli
{
// 放入队列
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root)
{
ArrayList<Integer> printList = new ArrayList<Integer>();
ArrayList<TreeNode> list = new ArrayList<TreeNode>();
if (root == null)
return printList;
list.add(root);
// 遍历队列中的元素,遍历过程中,访问该元素的左右节点,再将左右子节点加入到队列中来
for (int i = 0; i < list.size(); i++)
{
TreeNode node = list.get(i);
if (node.left != null)
{
list.add(node.left);
}
if (node.right != null)
{
list.add(node.right);
}
printList.add(node.val);
}
return printList;
}
public static void main(String[] args)
{
TreeNode root = new TreeNode(8);
root.left = new TreeNode(6);
root.right = new TreeNode(10);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(7);
root.right.left = new TreeNode(9);
root.right.right = new TreeNode(11);
Solution_cengcibianli s = new Solution_cengcibianli();
ArrayList<Integer> printList = new ArrayList<Integer>();
printList = s.PrintFromTopToBottom(root);
for (int i = 0; i < printList.size(); i++)
{
System.out.print(printList.get(i) + " ");
}
}
}
java实现从上往下打印出二叉树的每个节点,同层节点从左至右打印。
最新推荐文章于 2021-04-09 13:34:01 发布