二叉树遍历

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class traversal {
    //先序遍历
    public void preOrderRecursionTraverse(TreeNode root){
        if(root==null){
            return;
        }
        System.out.print(root.val);
        preOrderRecursionTraverse(root.left);
        preOrderRecursionTraverse(root.right);
    }
    //中序遍历
    public void inOrderRecursionTraverse(TreeNode root){
        if(root==null){
            return;
        }
        preOrderRecursionTraverse(root.left);
        System.out.print(root.val);
        preOrderRecursionTraverse(root.right);
    }
    //后序遍历
    public void postOrderRecursionTraverse(TreeNode root){
        if(root==null){
            return;
        }
        preOrderRecursionTraverse(root.left);
        preOrderRecursionTraverse(root.right);
        System.out.print(root.val);
    }
    //层序遍历
    public void levelOrderTraverse(TreeNode root){
      if(root==null){
          return;
      }
      Queue<TreeNode> queue=new LinkedList<TreeNode>();
      queue.add(root);
      while(!queue.isEmpty()){
          TreeNode node=queue.poll();
          System.out.print(node.val+"->");
          if(node.left!=null){
              queue.add(node.left);
          }
          if(node.right!=null){
              queue.add(node.right);
          }
      }
  }
}

 

posted @ 2021-02-20 08:59  Heinrich♣  阅读(25)  评论(0编辑  收藏  举报