这道题用C++来写,在本地执行正常,但是使用OJ判断输出结果是空,暂时不清楚原因。代码如下:

class Solution {
public:
    vector<int> V;
    //中序遍历
    void MidTree(TreeNode node)
    {
        if (&node != NULL)
        {
            if (node.left != NULL)
            {
                MidTree(*node.left);
            }
            V.push_back(node.val);
            if (node.right != NULL)
            {
                MidTree(*node.right);
            }
        }
    }

    TreeNode Join(TreeNode* t, int ct)
    {
        if (ct == V.size() - 1)
        {
            TreeNode tt = TreeNode(V[ct]);
            return tt;
        }
        TreeNode d = TreeNode(V[ct + 1]);
        TreeNode* dd = &d;
        TreeNode n = Join(dd, ct + 1);
        t->right = &n;
        return *t;
    }

    TreeNode* increasingBST(TreeNode* root) {
        MidTree(*root);
        TreeNode T = TreeNode(V[0]);
        TreeNode* TT = &T;
        TreeNode x = Join(TT, 0);
        return &x;
    }
};

 保留原有逻辑,修改为C#代码,则通过所有测试,代码如下:

public class Solution
    {
        public List<int> V = new List<int>();
        //中序遍历
        public void MidTree(TreeNode node)
        {
            if (node != null)
            {
                if (node.left != null)
                {
                    MidTree(node.left);
                }
                V.Add(node.val);
                if (node.right != null)
                {
                    MidTree(node.right);
                }
            }
        }

        public TreeNode Join(TreeNode t, int ct)
        {
            if (ct == V.Count() - 1)
            {
                TreeNode tt =new TreeNode(V[ct]);
                return tt;
            }
            TreeNode d = new TreeNode(V[ct + 1]);            
            TreeNode n = Join(d, ct + 1);
            t.right = n;
            return t;
        }
        public TreeNode IncreasingBST(TreeNode root)
        {
            MidTree(root);
            TreeNode T =new TreeNode(V[0]);            
            TreeNode x = Join(T, 0);
            return x;
        }
    }

不知是leetcode的判断机制问题,还是我的C++写法的问题。之后还是尽量使用C#吧。

posted on 2018-09-29 00:29  Sempron2800+  阅读(140)  评论(0编辑  收藏  举报