题解 | #二叉树的下一个结点#

二叉树的下一个结点

http://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e

/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
import java.util.*;
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        TreeLinkNode root = pNode;
        while (null != root.next) {
            root = root.next;
        }
        Stack<TreeLinkNode> stack = new Stack<>();
        Queue<TreeLinkNode> queue = new LinkedList<>();
        TreeLinkNode copyNode = pNode;
        pNode = root;
        while (null != pNode) {
            stack.push(pNode);
            pNode = pNode.left;
        }
        while (!stack.isEmpty()) {
            pNode = stack.pop();
            queue.add(pNode);
            if (null != pNode.right) {
                pNode = pNode.right;
                while (null != pNode) {
                    stack.push(pNode);
                    pNode = pNode.left;
                }
            }
        }
        while (queue.poll() != copyNode);
        pNode = null;
        if (!queue.isEmpty()) {
            pNode = queue.poll();
        }
        return pNode;
    }
}
全部评论

相关推荐

屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
LazyBreeze:项目尽量体现你对技术的理解和深度,不是说把中间件用一下就完事了,你项目里面提到集群和分布式,你真在服务器上部署过吗,感觉太假了,第二个项目说自己用了微服务的什么组件,只是用了没有自己的思考,很难让面试官注意到你的简历。针对某几个技术点自己多思考一下,考虑一下有没有别的替代方案,可以写一下,即使没有真的实现
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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