226. Invert Binary Tree
Link
難易度 : Easy
同樣是binary tree的題目,這次給了一個root並且要求我們將tree整個對稱翻轉
那麼這題其實想法十分單純
- 由上而下遍尋所有node
- 每遇到一個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;
}
}
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;
}
}
有時候解完題目還是多少會有點很懶惰的嘗試其他解法,但是又覺得好像多試點方法沒壞處QQ