LeetCode 105-106. Construct Binary Tree from Inorder and Postorder Traversal

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

解题思路:

根据二叉树的遍历性质我们知道,后续遍历的最后一个节点就是重建二叉树的根节点,然后根据此节点扫描中序遍历得到相应索引,索引左边的即为根节点左子树,索引右边为根节点的右子树。以此思想递归建立二叉树。

//利用中序和后序遍历建立二叉树
	 public static TreeNode buildTree(int[] inorder, int[] postorder) {
	    return helper(postorder.length-1, 0, inorder.length - 1, postorder, inorder);
	}

	public static TreeNode helper(int postStart, int inStart, int inEnd, int[] postorder, int[] inorder) {
	    if (postStart < 0 || inStart > inEnd) 
	    {
	        return null;
	    }
	    TreeNode root = new TreeNode(postorder[postStart]);
	    int inIndex = 0; 
	    for (int i = inStart; i <= inEnd; i++) {
	        if (inorder[i] == root.val) {
	            inIndex = i;
	        }
	    }
	  //减去右子树的节点数量,即可求出左子树的根节点
	    root.left = helper(postStart-(inEnd-inIndex)-1, inStart, inIndex-1, postorder, inorder);
	    root.right = helper(postStart -1, inIndex+1, inEnd, postorder, inorder);
	    
	    return root;
	}

下面是根据前序和中序遍历数组建立二叉树,思想大致同上:

 public  TreeNode buildTree(int[] preorder, int[] inorder) {
	    return helper(0, 0, inorder.length - 1, preorder, inorder);
	}

	public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
	    if (preStart > preorder.length - 1 || inStart > inEnd) 
	    {
	        return null;
	    }
	    TreeNode root = new TreeNode(preorder[preStart]);
	    int inIndex = 0; 
	    for (int i = inStart; i <= inEnd; i++) {
	        if (inorder[i] == root.val) {
	            inIndex = i;
	        }
	    }
	    root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);
	    root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);
	    return root;
	}

猜你喜欢

转载自blog.csdn.net/qq_30122883/article/details/86482525