
简单的二叉树遍历算法,
为了通过给定的先序遍历(preorder)和中序遍历(inorder)数组构造二叉树,我们需要理解这两种遍历方式的特点:
-  
先序遍历(Preorder):首先访问根节点,然后遍历左子树,最后遍历右子树。
 -  
中序遍历(Inorder):首先遍历左子树,然后访问根节点,最后遍历右子树。
 
利用这些特点,我们可以采用递归的方式构建二叉树。
基本思路是:
-  
先序遍历的第一个元素总是当前子树的根节点。
 -  
在中序遍历中找到这个根节点的位置,它左侧的所有元素都属于左子树,右侧的所有元素都属于右子树。
 -  
递归地构造左子树和右子树,左子树的先序遍历和中序遍历分别是原先序遍历中根节点之后的部分和中序遍历中根节点左侧的部分;右子树的先序遍历和中序遍历分别是原先序遍历中左子树之后的部分和中序遍历中根节点右侧的部分。
 
代码如下:
import javax.swing.tree.TreeNode;
public class buildTree {
    // 给定两个数组 preorder和inorder 一个线序遍历,一个中序遍历,请构造二叉树并返回其根节点
    class Solution{
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(preorder == null || inorder==null || preorder.length != inorder.length){
                return null;
            }
            return buildTreeHelper(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
        }
        public TreeNode buildTreeHelper(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart,int inEnd){
            if(preStart > preEnd||inStart > inEnd){
                return null;
            }
            // 先序遍历的第一个元素就是根节点
            TreeNode root=new TreeNode(preorder[preStart]);
            // 在中序遍历中找到根节点的位置
            int rootIndexInorder = inStart;
            while(rootIndexInorder <= inEnd&&inorder[rootIndexInorder]!=root.val){
                rootIndexInorder++;
            }
            int leftSubtreeSize=rootIndexInorder-inStart;
            //递归构建左子树和右子树
            root.left=buildTreeHelper(preorder,preStart+1,preStart+leftSubtreeSize,inorder,inStart,rootIndexInorder-1);
            root.right = buildTreeHelper(preorder, preStart + leftSubtreeSize + 1, preEnd, inorder, rootIndexInorder + 1, inEnd);
            return root;
        }
    }
}
 
                

















