LeetCode -- Invert Binary Tree
題目描述:
Invert a binary tree.
4
/
2 7
/ /
1 3 6 9
to
4
/
7 2
/ /
9 6 3 1
就是把一棵二叉樹進行反轉。
思路:
本題的實現比較直接:後續遍歷,交換節點。
實現代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode InvertTree(TreeNode root)
{
Travel(ref root);
return root;
}
private void Travel(ref TreeNode current)
{
if(current == null || current.left == null && current.right == null){
return;
}
Travel(ref current.left);
Travel(ref current.right);
Swap(ref current);
}
private void Swap(ref TreeNode n)
{
var tmp = n.left;
n.left = n.right;
n.right = tmp;
}
}