Leetcode DFS

100. Same

TreeGiven two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input: 1 1
/ \ /
2 3 2 3

    [1,2,3],   [1,2,3]

Output: true

class Solution {
    // recrusion
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null && q != null || p != null && q == null) return false;
        if(p.val == q.val){
           return isSameTree(p.left,q.left)&& isSameTree(p.right,q.right);
        }
        else return false;    
        
    }    
}

101. Symmetric Tree

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

class Solution {
	// recrusion
    public boolean isSymmetric(TreeNode root) {
       return root==null || Symmetric(root.left,root.right);
    }
    
    private boolean Symmetric(TreeNode left, TreeNode right)
    {   
        if (left == null || right == null) return left == right;
     
        if(left.val ==right.val)
            return Symmetric(left.left,right.right)&& Symmetric(left.right,right.left);
        else return false;
    }
}


class Solution {
    //iteration
    public boolean isSymmetric(TreeNode root) 
    {   
        if(root==null) return true;
        Stack<TreeNode> stack = new Stack<TreeNode> ();
        stack.push(root.left);
        stack.push(root.right);
        while(!stack.isEmpty())
        {
            TreeNode right = stack.pop();
            TreeNode left = stack.pop();
            if(left==null && right ==null) continue;
            if(left == null|| right== null || left.val!= right.val) return false;
            stack.push(left.left);
            stack.push(right.right);
            stack.push(left.right);
            stack.push(right.left);
        }
        return true;
    }
}
发布了12 篇原创文章 · 获赞 0 · 访问量 894

猜你喜欢

转载自blog.csdn.net/EPFL_Panda/article/details/100780297