[leet code] Symmetric Tree

来源:互联网 发布:html与javascript分离 编辑:程序博客网 时间:2024/04/29 15:06

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1   / \  2   2 / \ / \3  4 4  3

But the following is not:

    1   / \  2   2   \   \   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

binary tree本能反应递归. 然后分析该对称树, 我们无法使用一个参数进行递归, 不然的话就变成了子树内部对称.  于是考虑新建一个function并设置参数为左子树root, 与右子树root, 而我们需要检验的是这两颗子树对称.

分析到树的第三层时后我们得到了规律, 在一次递归当中两树对称当左节点的左子节点值等于右节点的有节点值, 并且左节点的右子结点值等于右节点的左节点值.

而递归的出口为: 

左右节点只有一个存在返回false

左右节点都存在且不等返回false

左右节点都不存在则返回true

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSymmetric(TreeNode root) {        if (root == null) return true;                TreeNode node = root;                return checkSymmetric(node.left, node.right);    }        public boolean checkSymmetric(TreeNode left, TreeNode right){        if (left == null || right == null) {            if (left != null || right != null) return false;            else return true;        }                if (left.val != right.val) return false;                return checkSymmetric(left.left, right.right) && checkSymmetric(left.right, right.left);    }}


递归转非递归第一反应要用栈!! 本题递归需要用到两个参数, 相应地需要创建两个栈, 一个储存左子树, 另一个储存右子树.

每一次循环, 将两栈当前节点出栈, 然后对比(对比逻辑与递归相同).  如果两节点完全相同, 则左栈压入左栈当前节点的左子节点, 右子结点, 相应地右栈压入右栈当前节点的右子节点, 左子节点. (出栈的时候正好两边对比).

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSymmetric(TreeNode root) {        if (root == null) return true;                Stack<TreeNode> left = new Stack<TreeNode>();        Stack<TreeNode> right = new Stack<TreeNode>();                left.push(root.left);        right.push(root.right);        // note that even push null, there will be a null pushed into the stack!!                while (!left.isEmpty() && !right.isEmpty()){            TreeNode nodeLeft = left.pop();            TreeNode nodeRight = right.pop();                        if(nodeLeft == null || nodeRight ==null){                if(nodeLeft != null || nodeRight != null) return false;            }            else{                if (nodeLeft.val != nodeRight.val) return false;                left.push(nodeLeft.left);                left.push(nodeLeft.right);                right.push(nodeRight.right);                right.push(nodeRight.left);            }        }        return true;    }}



0 0
原创粉丝点击