2014年5月9日星期五

Recursive Binary Tree Solution - Symmetric Tree

No matter the same tree for mirror/symmetric, or two separate trees, create a method pass in either two roots or root.left & root.right… edge condition, == … and recursively function to compare root1.left vs root2.right and root1.right vs root2.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;
        }
        if(root.left == null && root.right == null){
            return true;
        }
        return isSymmetricOperation(root.left, root.right);
    }
   
    private boolean isSymmetricOperation(TreeNode leftNode, TreeNode rightNode){
        if(leftNode != null && rightNode != null){
            if(leftNode.val != rightNode.val){
                return false;
            }else{
                return isSymmetricOperation(leftNode.left, rightNode.right) && isSymmetricOperation(leftNode.right, rightNode.left);
            }
        }else if(leftNode == null && rightNode == null){
            return true;
        }else{
            return false;
        }
    }
}

没有评论: