Accept C# Solution. Iterate and Recursive


  • 1
    M
        public IList<int> InorderTraversal(TreeNode root)
        {
            var result = new List<int>();
            if (root == null) return result;
    
            var stack = new Stack<TreeNode>();
            var cur = root;
            while (cur!=null || stack.Any())
            {
                while(cur!=null) 
                {
                    stack.Push(cur);
                    cur = cur.left;
                }
    
                cur = stack.Pop();
                result.Add(cur.val);
                cur = cur.right;
            }
            return result;
        }
        
        public IList<int> InorderTraversal2(TreeNode root)
        {
            var result = new List<int>();
            if (root == null) return result;
            TreeTravel(root, result);
            return result;
        }
    
        public void TreeTravel(TreeNode root, IList<int> result)
        {
            if(root.left!=null) TreeTravel(root.left, result);
            result.Add(root.val);
            if(root.right!=null) TreeTravel(root.right, result);
        }

Log in to reply
 

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