LeetCode-Invert Binary Tree

来源:互联网 发布:如何分析数据spss 编辑:程序博客网 时间:2024/06/05 10:55

tree一般就用recursion 还需要继续练习

需要注意的是recursion总是和循环写混乱,并不需要loop了

最开始我把if写成了while

public class Solution {    public TreeNode invertTree(TreeNode root) {        if ( root == null )            return null;        if ( root.left != null || root.right != null ){            TreeNode temp = root.left;            root.left = root.right;            root.right = temp;            invertTree( root.left );            invertTree( root.right );                    }        return root;    }}
记住先要判断root是不是null再访问它的left right

The above solution is correct, but it is also bound to the application stack, which means that it's no so much scalable - (you can find the problem size that will overflow the stack and crash your application), so more robust solution would be to use stack data structure.

public class Solution {    public TreeNode invertTree(TreeNode root) {        if (root == null) {            return null;        }        final Deque<TreeNode> stack = new LinkedList<>();        stack.push(root);        while(!stack.isEmpty()) {            final TreeNode node = stack.pop();            final TreeNode
//BFS <pre name="code" class="java">public class Solution {    public TreeNode invertTree(TreeNode root) {        if (root == null) {            return null;        }        final Queue<TreeNode> queue = new LinkedList<>();        queue.offer(root);        while(!queue.isEmpty()) {            final TreeNode node = queue.poll();            final TreeNode left = node.left;            node.left = node.right;            node.right = left;            if(node.left != null) {                queue.offer(node.left);            }            if(node.right != null) {                queue.offer(node.right);            }        }        return root;    }}

left = node.left; node.left = node.right; node.right = left; if(node.left != null) { stack.push(node.left); } if(node.right != null) { stack.push(node.right); } } return root; }}


Finally we can easly convert the above solution to BFS - or so called level order traversal.


0 0
原创粉丝点击