翻轉二叉樹

問題描述:

翻轉一棵二叉樹
樣例
  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

解題思路:

運用遞歸方式,將二叉樹的左、右子樹交換

代碼:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    void invertBinaryTree(TreeNode *root) {
        if(root==NULL) return;
        else{
         invertBinaryTree(root->left);
         invertBinaryTree(root->right);
         TreeNode*q=root->left;
         root->left=root->right;
         root->right=q;
          }
           // write your code here
    }
};

感想:

不能直接在遞歸過程中將左、右子樹交換,注意類的返回類型爲空

發佈了49 篇原創文章 · 獲贊 0 · 訪問量 5008
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章