leetcode623+給tree加一層值,遞迴
阿新 • • 發佈:2018-12-14
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: void dfs(TreeNode* r, int cur_d, int v, int d) { if(r==NULL) return; if(cur_d == d-1){ TreeNode *new_left = new TreeNode(v); TreeNode *new_right = new TreeNode(v); new_left->left = r->left; new_right->right = r->right; r->left = new_left; r->right = new_right; } dfs(r->left, cur_d+1, v, d); dfs(r->right, cur_d+1, v, d); } TreeNode* addOneRow(TreeNode* root, int v, int d) { if(d==1){ TreeNode *new_root = new TreeNode(v); new_root->left = root; return new_root; } dfs(root, 1, v, d); return root; } };