1,判断二叉树是否对称
1 |
|
/ \ |
|
2 2 |
|
/ \ / \ |
|
3 4 4 3 |
递归:
基本想法就是在函数中传入一边的左,和一边的右……
isSymmetric(leftNode.left, rightNode.right)
isSymmetric(leftNode.right, rightNode.left)
以这样的递归来不断比较。
public class SymmetricTree { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public boolean isSymmetric(TreeNode root) { if(root == null) return true; return isSymmetric(root.left, root.right); } public boolean isSymmetric(TreeNode leftNode, TreeNode rightNode){ if(leftNode == null && rightNode == null ) return true; if(leftNode == null || rightNode == null) return false; if(leftNode.val != rightNode.val) return false; boolean isLeft = isSymmetric(leftNode.left, rightNode.right); boolean isRight = isSymmetric(leftNode.right, rightNode.left); return isLeft && isRight; } public static void main(String args[]){ TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(2); root.left.left = new TreeNode(3); root.left.right = new TreeNode(4); root.right.left = new TreeNode(4); root.right.right = new TreeNode(3); System.out.println(new SymmetricTree().isSymmetric(root)); System.out.println(new SymmetricTree().isSymmetricIter(root)); } }
非递归的思路,就是分别遍历左右两边。只不过是反着次序遍历。
每次都各自出栈后往各自栈中放左右节点。一边是先放左后放右,一边是先放右后放左。
public boolean isSymmetricIter(TreeNode root) { if(root == null) return true; Stack<TreeNode> leftStack = new Stack<TreeNode>(); Stack<TreeNode> rightStack = new Stack<TreeNode>(); leftStack.push(root.left); rightStack.push(root.right); while (leftStack.size() > 0 && rightStack.size() > 0){ TreeNode left = leftStack.pop(); TreeNode right = rightStack.pop(); if(left == null && right == null) continue; if(left == null || right == null) return false; if(left.val == right.val) { leftStack.push(left.right); leftStack.push(left.left); rightStack.push(right.left); rightStack.push(right.right); }else{ return false; } } return true; }
时间: 2024-11-06 07:30:11