Leetcode - Construct Binary Tree from Inorder and Postorder Traversal

**
Question:

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

Note:
You may assume that duplicates do not exist in the tree.
**

谁能告诉我,为什么上面我加了 ** ,也没能将字体加粗吗?今天研究了下Markdown,也没找到问题所在。求大神指点啊。。。


My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length == 0)
            return null;
        int headKey = postorder[postorder.length - 1];
        TreeNode node = this.formBiTree(inorder, postorder, headKey);
        return node;
    }
    
    private TreeNode formBiTree(int[] inorder, int[] postorder, int headKey) {
        if (inorder.length == 1) {
            TreeNode leafNode = new TreeNode(headKey);
            leafNode.left = null;
            leafNode.right = null;
            return leafNode;
        }
        boolean isLeftEmpty = false;
        boolean isRightEmpty = false;
        int headValue = headKey;
        int sentinel = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (headValue == inorder[i]) {
                sentinel = i;
                break;
            }
        }
        /* get the key of both left and right */
        int leftKey = 0;
        int rightKey = 0;
        if (sentinel == 0)
            isLeftEmpty = true;
        else
            leftKey = postorder[sentinel - 1];
        
        if (sentinel == inorder.length - 1)
            isRightEmpty = true;
        else
            rightKey = postorder[postorder.length - 2];
        
        /* get the inorder and postorder of both left and right */
        TreeNode head = new TreeNode(headValue);
        
        int[] leftInorder;
        int[] leftPostorder;
        if (!isLeftEmpty) {
            leftInorder = new int[sentinel];
            for (int i = 0; i < leftInorder.length; i++)
                leftInorder[i] = inorder[i]; 
            
            leftPostorder = new int[sentinel];
            for (int i = 0; i < leftPostorder.length; i++)
                leftPostorder[i] = postorder[i];
            
            head.left = formBiTree(leftInorder, leftPostorder, leftKey);
        }
        else
            head.left = null;
        
        int[] rightInorder;
        int[] rightPostorder;
        if (!isRightEmpty) {
            rightInorder = new int[inorder.length - sentinel - 1];
            for (int i = 0; i < rightInorder.length; i++)
                rightInorder[i] = inorder[i + sentinel + 1];
            
            rightPostorder = new int[inorder.length - sentinel - 1];
            for (int i = 0; i < rightPostorder.length; i++)
                rightPostorder[i] = postorder[i + sentinel];
            
            head.right = formBiTree(rightInorder, rightPostorder, rightKey);
        }
        else
            head.right = null;
        
        return head;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[] a = {4, 2, 7, 5, 8, 1, 3, 9, 6};
        int[] b = {4, 7, 8, 5, 2, 9, 6, 3, 1};
        System.out.println(test.buildTree(a, b).val);   
    }
}

My test result:

Paste_Image.png

这次的难度提前查了下,害怕又像昨天一样,碰到了一道hard题目一开始没引起重视。还好,是medium。还算应付的来。
先去洗个澡儿。回来写。


coming back

这次题目就是给你两个 数列,一个是inorder遍历tree得到的数组,一个是postorder遍历tree得到的数组。根据这两个数列,还原出原tree。
首先,我们得明白什么是inorder, postorder。
下面是维基百科的解释

Paste_Image.png
Paste_Image.png

pre-order: 中-左-右
in-order: 左-中-右
post-order: 左-右-中
现在假设我们有这样的一棵树。

Paste_Image.png

inorder:
A B C D E F G H I
4 2 7 5 8 1 3 9 6

postorder:
A C E D B H I G F
4 7 8 5 2 9 6 3 1

因为数组是int,所以用数字来代替字母。
然后我们可以发现,由于postorder遍历的原理,postorder[] 的最后一位一定是头结点。
于是找到了这个头结点。
然后遍历inorder[],找到这个Value对应的Key值,这个key值就是数组里头结点的index。
然后,由于inorder遍历的特性,其左边一定是左支树,右边是右支树。于是断成两个sub inorder array.
同时,我们可以根据头结点在inorder中的index,将postorder array同样分裂为两个sub postorder array.
这样,我们就有了左支树的inorder array and post array,也有了右支树的。
然后就可以再次调用该函数,其实就是递归啦。一次递归下去,直到最后完成树上所有结点的构建。
两个注意点:
1.一开始传进来的array可能为空,需要进行判断。这里卡了我很久。
2.遍历到最后,可能出现分出来的左支树或者右支树为空,会造成arrayIndexOutOfBounded Exception. 需要注意这个情况。

**
总结:
pre-order
in-order
post-order

recursion
**
之前说的函数编程和动态规划很是复杂。我的能力还不足以概括,给出链接。
函数编程:
http://www.zhihu.com/question/28292740

动态规划:
http://www.zhihu.com/question/23995189

这是我觉得写的挺不错的两个专栏。有时间在研究。
然后答应的C来写面向对象和C++中的模板与继承,还正在看,火候还不够。明后天总结。

要考试了额。。。到现在学校考试的题目还没有刷。。。

Anyway, Good luck, Richardo!

为什么我之前的代码写的这么复杂。。。懒得看了,贴上这次我写的代码
My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || inorder.length == 0)
            return null;
        if (postorder == null || postorder.length == 0)
            return null;
        return helper(0, postorder.length - 1, 0, inorder.length - 1, postorder, inorder);
    }
    
    private TreeNode helper(int p1, int p2, int i1, int i2, int[] postorder, int[] inorder) {
        if (p2 <= p1) {
            return new TreeNode(postorder[p1]);
        }
        int head = postorder[p2];
        int headInorder = 0;
        for (int i = i1; i <= i2; i++) {
            if (inorder[i] == head) {
                headInorder = i;
                break;
            }
        }
        TreeNode headNode = new TreeNode(head);
        int leftNum = headInorder - i1;
        if (leftNum > 0) {
            headNode.left = helper(p1, p1 + leftNum - 1, i1, i1 + leftNum - 1, postorder, inorder);
        }
        if (leftNum + 1 < p2 - p1 + 1) {
            headNode.right = helper(p1 + leftNum, p2 - 1, headInorder + 1, i2, postorder, inorder);
        }
        return headNode;
    } 
}

感觉思路比以前清楚多了。

Anyway, Good luck, Richardo!

My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || postorder == null || inorder.length != postorder.length) {
            return null;
        }
        
        return helper(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
    }
    
    private TreeNode helper(int[] inorder, int[] postorder, int inLo, int inHi, int postLo, int postHi) {
        if (inLo > inHi) {
            return null;
        }
        else if (inLo == inHi) {
            return new TreeNode(inorder[inLo]);
        }
        else {
            TreeNode root = new TreeNode(postorder[postHi]);
            int index = 0;
            for (int i = inLo; i <= inHi; i++) {
                if (inorder[i] == postorder[postHi]) {
                    index = i;
                    break;
                }
            }
            
            root.left = helper(inorder, postorder, inLo, index - 1, postLo, postLo + index - inLo - 1);
            root.right = helper(inorder, postorder, index + 1, inHi, postLo + index - inLo, postHi - 1);
            return root;
        }
    }
}

感觉就是 Binary search 的一个改编版。不难

Anyway, Good luck, Richardo! --- 08/06/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容