树的遍历

来源:互联网 发布:布谷鸟算法 编辑:程序博客网 时间:2024/05/20 15:37

1、层序遍历

public class Solution {    ArrayList<Integer> list = new ArrayList<>();        ArrayList<TreeNode> nodes = new ArrayList<>();    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {        if(root !=null){            nodes.add(root);            while(nodes.size() !=0){                TreeNode n = nodes.remove(0);//删除并返回头结点                list.add(n.val);                if(n.left!=null){                    nodes.add(n.left);                }                if(n.right!=null){                    nodes.add(n.right);                }            }        }        return list;    }}

2、前序遍历

public class Solution {    ArrayList<Integer> list = new ArrayList<>();        public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {        if(root !=null){             list.add(root.val); //根             PrintFromTopToBottom(root.left); //左             PrintFromTopToBottom(root.right); //右        }        retrun list;}     
原创粉丝点击