zoukankan      html  css  js  c++  java
  • [算法题] 重建二叉树

    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

    题目思路

    本题就是按照建立二叉树的思路建立就行了。先序遍历的第一个是根节点,然后在中序遍历找到该根节点,以此为界,中序遍历的左边是它的左子树的中序遍历,同样地找到该左子树在先序遍历中对应的先序遍历顺序。对于右子树也是一样的方法。

    本体采用递归,递归就要先写出终止条件。

    Python代码

    这个题目用Python非常方便,因为可以直接利用到Python中的切片技术,省时省力通俗易懂。Java版本相对复杂得多。

    # -*- coding:utf-8 -*-
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        # 返回构造的TreeNode根节点
        def reConstructBinaryTree(self, pre, tin):
            # write code here
            if len(pre)==0 or len(tin)==0:
                return
            if len(pre)==1:
                return TreeNode(pre[0])
            node=TreeNode(pre[0])
            for i in range(len(tin)):
                if tin[i]==pre[0]:
                    break
            node.left=self.reConstructBinaryTree(pre[1:i+1],tin[:i])
            node.right=self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
            return node

     JAVA代码

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            if (pre==null || in == null){
                return null;
            }
            return doIt(pre,in,0,pre.length-1,0,in.length-1);
            
        }
        public TreeNode doIt(int [] pre,int [] in,int pre_start,int pre_stop,int in_start, int in_stop) {
            TreeNode node =new TreeNode(pre[pre_start]);
            node.left=null;
            node.right=null;
            int i;
            for(i=in_start;i<=in_stop;i++){
                if (in[i]==pre[pre_start])
                    break;
            }
            if(i>in_start){
            node.left=doIt(pre,in,pre_start+1,pre_start+i-in_start,in_start,i-1);
            }
            if (i<in_stop){
            node.right=doIt(pre,in,pre_start+i-in_start+1,pre_stop,i+1,in_stop);
            }
            return node;
        }
    }

    我们可以发现,Java没有切片技术,因此pre 和 in两个数组分别设立了两个指针,共计四个。调整这四个指针的值是一件技术活,很不直观,需要自己慢慢Debug=。=

    因此,Python这种接近于伪代码的语法特性使得程序员更加关注算法本身而不是一些细节。

    不过写Java确实练技术。

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    from Zen of Python
  • 相关阅读:
    Pentaho
    sympy 解四元一次方程
    install R language on ubuntu
    pyside
    浙江省医院网上挂号
    mtu值相关
    Python 中除法运算需要注意的几点
    idea
    kilim
    good blog
  • 原文地址:https://www.cnblogs.com/chengyuanqi/p/7351920.html
Copyright © 2011-2022 走看看