• Construct Binary Tree from Preorder and Inorder Traversal


    问题描述

    Given preorder and inorder traversal of a tree, construct the binary tree.

    解决思路

    首先确定根节点,然后确定左右子树的节点数目。依次递归即可。

    假设输入的序列均合法。

    程序

    public class BuildTreeFromPreorderAndInorder {
    	public TreeNode buildTree(int[] preorder, int[] inorder) {
    		if (preorder == null || inorder == null || preorder.length == 0
    				|| preorder.length != inorder.length) {
    			return null;
    		}
    		int len = preorder.length;
    		TreeNode root = buildHelper(preorder, 0, len - 1, inorder, 0, len - 1);
    		return root;
    	}
    
    	private TreeNode buildHelper(int[] preorder, int pre_start, int pre_end,
    			int[] inorder, int in_start, int in_end) {
    		// bound
    		if (pre_start > pre_end || in_start > in_end) {
    			return null;
    		}
    
    		int rootVal = preorder[pre_start];
    		TreeNode root = new TreeNode(rootVal);
    		// find root-val in inorder list
    		int i = 0;
    		for (; i <= in_end; i++) {
    			if (inorder[i] == rootVal) {
    				break;
    			}
    		}
    
    		int leftLen = i - in_start;
    		root.left = buildHelper(preorder, pre_start + 1, pre_start + leftLen,
    				inorder, in_start, i - 1);
    		root.right = buildHelper(preorder, pre_start + leftLen + 1, pre_end,
    				inorder, i + 1, in_end);
    
    		return root;
    	}
    }
    

    Follow up

    如果给定的是中序和后序遍历序列,如何构建二叉树?

    解决思路是类似的。

    程序

    public class BuildTreeFromInorderAndPostorder {
    	public TreeNode buildTree(int[] inorder, int[] postorder) {
    		if (inorder == null || postorder == null || inorder.length == 0
    				|| inorder.length != postorder.length) {
    			return null;
    		}
    		int len = inorder.length;
    		TreeNode root = buildHelper(inorder, 0, len - 1, postorder, 0, len-1);
    		return root;
    	}
    
    	private TreeNode buildHelper(int[] inorder, int in_start, int in_end, int[] postorder,
    			int post_start, int post_end) {
    		if (in_start > in_end || post_start > post_end) {
    			return null;
    		}
    		
    		int rootVal = postorder[post_end];
    		TreeNode root = new TreeNode(rootVal);
    		
    		int i = in_start;
    		for (; i <= in_end; i++) {
    			if (inorder[i] == rootVal) {
    				break;
    			}
    		}
    		
    		int leftLen = i - in_start;
    		root.left = buildHelper(inorder, in_start, i-1, postorder, post_start, post_start+leftLen-1);
    		root.right = buildHelper(inorder, i+1, in_end, postorder, post_start+leftLen, post_end - 1);
    		
    		return root;
    	}
    }
    

      

  • 相关阅读:
    程序员你写的代码,被爆出黑产了!
    .NET面试题系列之面向对象
    .NET必问的面试题系列之基本概念和语法
    xamarin开发android收集的一些工具
    C#爬虫使用代理刷csdn文章浏览量
    我们必须要知道的RESTful服务最佳实践
    MVP架构在xamarin android中的简单使用
    使用Xamarin实现跨平台移动应用开发(转载)
    博客园app for xamarin android一款简洁阅读的博客园android客户端
    vs2019企业版密钥
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4656412.html
Copyright © 2020-2023  润新知