面试题 04.06. 后继者

https://leetcode-cn.com/problems/successor-lcci/

这个题不是特别难,就是比较绕,按照中序遍历的当前节点的下一个结点分为两种

1.当前节点有右孩子,这种比较简单,直接找到右孩子的最左边的孩子就可以。

2.当前节点没有右孩子,要找到当前节点是父节点的左孩子的时候,返回其父节点。因为根据中序遍历的原则就是这样做的。。

最终做出来的答案可能比较垃圾,效率也是低的令人发指。

执行用时 :4 ms, 在所有 Java 提交中击败了45.81%的用户
内存消耗 :40.9 MB, 在所有 Java 提交中击败了100.00%的用户
不过好歹是AC了
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    LinkedList<TreeNode> stack = new LinkedList<>();
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        return helper(root,p);
    }

    private TreeNode helper(TreeNode root, TreeNode p){
        if(root == null){
            return null;
        }
        if(root.val == p.val) {
            if (root.right != null) {
                TreeNode cur = root.right;
                while(cur.left != null){
                    cur = cur.left;
                }
                return cur;
            } else {
                TreeNode cur = root;
                while (!stack.isEmpty()) {
                    TreeNode temp = stack.removeLast();
                    if (temp.left == cur) {
                        return temp;
                    }
                    cur = temp;
                }
            }
        }
        stack.add(root);
        TreeNode left = helper(root.left,p);
        TreeNode right = helper(root.right,p);
        if(!stack.isEmpty()) {
            stack.removeLast();
        }
        return left==null?right:left;
    }
}
原文地址:https://www.cnblogs.com/ZJPaang/p/12891580.html