【数据结构】二叉树相关操作

来源:互联网 发布:阿里云域名怎么绑定ip 编辑:程序博客网 时间:2024/05/17 06:03

1、二叉树的层次遍历(leetcode 102)

 //二叉树的层次遍历    //利用队列    public void FloorVisit(BinaryTree<T> root)    {        Queue<BinaryTree> queue = new LinkedList<BinaryTree>();        if(root==null)        {            return;        }        BinaryTree<T> current;        queue.offer(root);        while(!queue.isEmpty()) {            current = queue.peek();            queue.poll();            System.out.println(current.value);            if (current.left != null) {                queue.offer(current.left);            }            if (current.right != null) {                queue.offer(current.right);            }        }    }

2、求二叉树的节点个数

  //求二叉树的节点个数    public int numOfNodes(BinaryTree<T> root)    {        if(root==null)        {            return 0;        }        return (numOfNodes(root.left)+numOfNodes(root.right))+1;    }


3、求二叉树的深度(leetcode 104)

    //求二叉树的深度    public int depthOfTree(BinaryTree<T> root)    {        if(root==null)        {            return 0;        }        int left = depthOfTree(root.left);        int right = depthOfTree(root.right);        return (left>right?left:right)+1;    }


4、求二叉树的宽度

//求二叉树的宽度    public int widthOfTree(BinaryTree<T> root)    {        if(root==null)        {            return 0;        }        BinaryTree<T> current = root;        Queue<BinaryTree> queue = new LinkedList<BinaryTree>();        queue.offer(root);        int width = 0;        int tempWidth = queue.size();        while(tempWidth>0)        {            if(tempWidth>width)            {                width = tempWidth;            }            while(tempWidth>0)            {                current = queue.peek();                queue.poll();                if(current.left!=null)                {                    queue.offer(current.left);                }                if(current.right!=null)                {                    queue.offer(current.right);                }                tempWidth--;            }            tempWidth = queue.size();        }        return width;    }


5、判断两个树是否相同

 //判断两个树是否相同    public boolean isSameTree(BinaryTree<T> root1,BinaryTree<T> root2)    {        if(root1==null && root2==null)        {            return true;        }        if((root1!=null&&root2==null) || (root1==null && root2!=null))        {            return false;        }        if(root1.value!=root2.value)        {            return false;        }        return (isSameTree(root1.left,root2.left)&&isSameTree(root1.right,root2.right));    }


6、二叉树的镜像转换(leetcode 226)

 //二叉树的镜像转换    public void reverseTree(BinaryTree<T> root)    {        if(root==null)        {            return;        }        BinaryTree<T> temp = null;        temp = root.right;        root.right = root.left;        root.left = temp;        //递归调用,把所有的左子树和右子树翻转        reverseTree(root.left);        reverseTree(root.right);    }




0 0
原创粉丝点击