LintCode_175_翻轉二叉樹

翻轉二叉樹

翻轉一棵二叉樹

樣例
  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4
挑戰

遞歸固然可行,能否寫個非遞歸的?

寫的遞歸

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        // write your code here
        if(root != null){
            TreeNode i = root.left;
            root.left = root.right;
            root.right = i;
            invertBinaryTree(root.left);
            invertBinaryTree(root.right);
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章