翻轉二叉樹-LintCode

描述:

翻轉一棵二叉樹


樣例:

  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4

思路:

這個題就是遞歸調用 swap( , ) 函數,交換一個根節點的左右子樹。


代碼:

/**
 * 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) {
        // write your code here
        if(root==NULL)
        return;
        invertBinaryTree(root->left);
        invertBinaryTree(root->right);
        swap(root->left,root->right);
        
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章