Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
思路分析:
題意是將二叉樹所有左右子數(shù)對調(diào),如上圖所示。
具體做法是,先遞歸處理左右子樹,然后將當前的左右子樹對調(diào)。
代碼實現(xiàn):
/*** 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.left=invertTree(root.left);}if(root.right!=null){root.right=invertTree(root.right);}TreeNode temp=root.right;root.right=root.left;root.left=temp;return root;} }總結(jié)
以上是生活随笔為你收集整理的Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 104. Ma
- 下一篇: Leet Code OJ 283. Mo