题目链接:https://leetcode.com/problems/invert-binary-tree/
题目
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
解题思路:
1、先序遍历二叉树
2、若当前节点是分支节点,则交换该节点左右子树
注意:
1、初始要判断根节点是否为空
2、分支节点有两种情况:左右子树都不为空,左子树为空或右子树为空
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null)
return null;
if(root.left != null || root.right != null) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
if(root.left != null)
invertTree(root.left);
if(root.right != null)
invertTree(root.right);
return root;
}
}
转载自原文链接, 如需删除请联系管理员。
原文链接:226 Invert Binary Tree,转载请注明来源!