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

二叉树的下一个结点

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;
    }
}
全部评论

相关推荐

07-07 12:25
门头沟学院 Java
程序员牛肉:你这个智邮公司做的就是那个乐山市税务系统的服务吗?
点赞 评论 收藏
分享
人力小鱼姐:实习经历没有什么含金量,咖啡店员迎宾这种就别写了,其他两段包装一下 想找人力相关的话,总结一下个人优势,结合校园经历里有相关性的部分,加一段自我评价
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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