[Leetcode in Java] 226. Invert Binary Tree


Posted by LarsonKao on 2022-06-04

226. Invert Binary Tree

Link

難易度 : Easy

question

同樣是binary tree的題目,這次給了一個root並且要求我們將tree整個對稱翻轉

那麼這題其實想法十分單純

  1. 由上而下遍尋所有node
  2. 每遇到一個node,就將node.left與node.right交換

這樣就可以很簡單明瞭的將整棵樹翻轉過來

這邊我分別使用recursive與iteratively的思路來實作

recursive

    //recursive
    class Solution
    {
        public TreeNode invertTree(TreeNode root)
        {
            if(root==null) 
            {
                return null;
            }
            TreeNode tmp = root.left;
            root.left=root.right;
            root.right=tmp;

            invertTree(root.left);
            invertTree(root.right);
            return root;
        }
    }

result

iteratively

    //iteratively
    class Solution2
    {
        public TreeNode invertTree(TreeNode root)
        {
            if(root==null) 
            {
                return root;
            }
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while(!stack.isEmpty()) 
            {
                TreeNode current = stack.pop();
                TreeNode tmp = current.left;
                current.left = current.right;
                current.right = tmp;
                if(current.left!=null) 
                {
                    stack.push(current.left);
                }
                if(current.right!=null) 
                {
                    stack.push(current.right);
                }
            }

            return root;
        }
    }

result

有時候解完題目還是多少會有點很懶惰的嘗試其他解法,但是又覺得好像多試點方法沒壞處QQ


#Leetcode #java #algorithm #binary tree







Related Posts

用 Nest.js 開發 API 吧 (五) - Postgresql

用 Nest.js 開發 API 吧 (五) - Postgresql

資訊安全概念

資訊安全概念

給工程師的 Sketch Prototyping 簡易入門教學

給工程師的 Sketch Prototyping 簡易入門教學


Comments