C語言遞歸之翻轉二叉樹

題目描述node

翻轉一棵二叉樹。網絡

 

示例ide

輸入:spa

     4
   /   \
  2     7
 / \   / \
1   3 6   9

輸出:code

     4
   /   \
  7     2
 / \   / \
9   6 3   1

 

題目要求blog

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 struct TreeNode* invertTree(struct TreeNode* root){
11 
12 }

 

題解遞歸

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 struct TreeNode* invertTree(struct TreeNode* root){
11     if(root==NULL)return root;
12     struct TreeNode *r=(struct TreeNode*)malloc(sizeof(struct TreeNode));
13     r->val=root->val;
14     if(root->left!=NULL)r->right=invertTree(root->left);
15     else r->right=NULL;
16     if(root->right!=NULL)r->left=invertTree(root->right);
17     else r->left=NULL;
18     return r;
19 }
題解

 

遞歸leetcode

遞歸須要明確終止條件、返回值、遞歸內容,二叉樹問題還需注意根節點爲空的特殊狀況。get

 

題目來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/invert-binary-tree/
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。it

相關文章
相關標籤/搜索