天天看點

leetcode-- Invert Binary Tree

反轉二叉樹。

leetcode-- Invert Binary Tree

解題思路:左右節點互換,然後遞歸調用即可。

java版本:

public class Solution {
    public TreeNode invertTree(TreeNode root) {

        if(root==null) {return root;}

        TreeNode tmp=invertTree(root.left);
        root.left=invertTree(root.right);
        root.right=tmp;
        return root;
    }
}
           

c++版本:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
     if(root==NULL)
      return NULL;
      TreeNode* temp=root->left;
      root->left=root->right;
      root->right=temp;
      root->left=invertTree(root->left);
      root->right=invertTree(root->right);
      return root;

    }
};
           

繼續閱讀