C# solution: stack, inorder


  • 0
    B
    public class Solution 
    {
        public TreeNode InorderSuccessor(TreeNode root, TreeNode p) 
        {
            var stack = new Stack<TreeNode>();
    
            var cur = root;
            while(cur != null)
            {
                stack.Push(cur);
                cur = cur.left;
            }
    
            bool isFindP = false;
    
            while(stack.Any())
            {
                cur = stack.Pop();
    
                if (isFindP) return cur;
    
                if (cur == p) isFindP = true;
    
                if (cur.right != null)
                {
                    cur = cur.right;
                    while(cur != null)
                    {
                        stack.Push(cur);
                        cur = cur.left;
                    }
                }
            }
    
            return null;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.