翻转二叉树

来源:互联网 发布:mac怎么将dock栏放大 编辑:程序博客网 时间:2024/04/28 12:41

1.问题描述:翻转一棵二叉树。

2.思路:正如样例

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

利用递归的思想交换左右节点,一层一层的往下遍历。

3.代码:

/** * 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;        else {  TreeNode *t=root->left;                root->left=root->right;                root->right=t;                invertBinaryTree(root->left);                invertBinaryTree(root->right);        }    }};

4.感想:感觉这个方法真的很巧妙!也觉得二叉树中的问题只要搞清楚了遍历就能有点思路了~

0 0
原创粉丝点击