Leetcode DFS

这篇博客探讨了如何使用深度优先搜索(DFS)解决LeetCode中的两个问题:100. Same Tree和101. Symmetric Tree。在100题中,任务是判断两棵二叉树是否结构相同且节点值相等;而在101题中,需要检查二叉树是否关于其中心对称。通过示例解释了判断标准和解题思路。

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值