题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

基本都是递归方法的题解,这里提供一个迭代方法的题解,方法很巧妙,具体思路来自leetcode-105
https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/cong-qian-xu-yu-zhong-xu-bian-li-xu-lie-gou-zao-9/

import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        int len = pre.length;
        if(len==0) return null;
        TreeNode root = new TreeNode(pre[0]);
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
        int inIndex = 0;
        for(int i=1;i<len;i++){
            int val = pre[i];
            TreeNode node = s.peek();
            if(node.val!=in[inIndex]){
                node.left = new TreeNode(val);
                s.push(node.left);
            }
            else{
                while(!s.isEmpty() && s.peek().val==in[inIndex]){
                    node = s.pop();
                    inIndex++;
                }
                node.right = new TreeNode(val);
                s.push(node.right);
            }
        }
        return root;
    }
}
全部评论

相关推荐

09-18 20:41
门头沟学院 Java
要个offer怎么这...:哈哈哈哈哈哈,我也拿了0x10000000个offer,秋招温啦啦啦,好开心
我的秋招日记
点赞 评论 收藏
分享
09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务