前序遍历
前序遍历首先访问根结点然后遍历左子树,最后遍历右子树。
前序遍历有个特点
- 节点的分布总是按照
根节点 左子树节点 右子树节点
依次排列。
中序遍历
中序遍历首先遍历左子树,再访问根节点,最后遍历右子树。
中序遍历有个特点
根节点
的左侧是左子树节点,右侧是右子树节点
。
依靠前序遍历和中序遍历的特点构建二叉树
leetcode 105
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0 || inorder.length==0) return null;
TreeNode root=new TreeNode(preorder[0]);
for(int i=0;i<preorder.length;i++){
if(preorder[0]==inorder[i]){
root.left=buildTree(Arrays.copyOfRange(preorder,1,i+1),Arrays.copyOfRange(inorder,0,i));
root.right=buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));
break;
}
}
return root;
}
}