Same Tree - LeetCode

题目链接

Same Tree - LeetCode

注意点

  • 先判断结点是否为空再访问结点的值

解法

解法一:递归,从根结点开始判断,然后递归判断左右子树。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(!p  && !q) return true;
        if((p && !q) || (!p && q) || (p->val != q->val)) return false;
        return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    }
};

解法二:非递归,和递归思想一样,但是显式的用栈来模拟递归的过程。

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int> >ret;
        vector<vector<int> >vec(1);
        for(int i = 1; i <= n; i++)
        {
            int len = vec.size();
            vector<int> tmp;
            for(int j = 0; j < len; j++)
            {
                tmp = vec[j];
                tmp.push_back(i);
                if(tmp.size() == k)ret.push_back(tmp);
                else vec.push_back(tmp);
            }
        }
        return ret;
    }
};

小结

  • 递归的本质就是利用栈实现的

猜你喜欢

转载自www.cnblogs.com/multhree/p/10500884.html